dprogs/ 0000755 0002457 0000456 00000000000 100145135dprogs/CameraTester.java.html dprogs/CausalLinker.java.html dprogs/CausalMessage.java.html dprogs/CentMutex.java.html dprogs/CentSensor.java.html dprogs/Chat.java.html dprogs/CircToken.java.html dprogs/Connector.java.html dprogs/Consensus.java.html dprogs/ConsensusTester.java.html dprogs/DSTerm.java.html dprogs/DatagramClient.java.html dprogs/DatagramServer.java.html dprogs/DinMutex.java.html dprogs/DirectClock.java.html dprogs/DistSensor.java.html dprogs/Election.java.html dprogs/FuncUser.java.html dprogs/GlobalFunc.java.html dprogs/GlobalFuncTester.java.html dprogs/GlobalService.java.html dprogs/IntLinkedList.java.html dprogs/KingBGA.java.html dprogs/LamportClock.java.html dprogs/LamportMutex.java.html dprogs/Linker.java.html dprogs/ListenerThread.java.html dprogs/Lock.java.html dprogs/LockTester.java.html dprogs/Matrix.java.html dprogs/MatrixClock.java.html dprogs/Message.java.html dprogs/MsgHandler.java.html dprogs/MsgList.java.html dprogs/Name.java.html dprogs/NameRmiClient.java.html dprogs/NameServer.java.html dprogs/NameService.java.html dprogs/NameServiceImpl.java.html dprogs/NameTable.java.html dprogs/PortAddr.java.html dprogs/Process.java.html dprogs/RAMutex.java.html dprogs/RecvCamera.java.html dprogs/RestartTask.java.html dprogs/RingLeader.java.html dprogs/SenderCamera.java.html dprogs/Sensor.java.html dprogs/SensorCircToken.java.html dprogs/SensorTester.java.html dprogs/SensorUser.java.html dprogs/SeqMessage.java.html dprogs/ShortestPath.java.html dprogs/SimpleSynch.java.html dprogs/SpanTree.java.html dprogs/StabTest.java.html dprogs/StableBottom.java.html dprogs/StableNormal.java.html dprogs/StableSpanNonroot.java.html dprogs/StableSpanRoot.java.html dprogs/StableTreeTester.java.html dprogs/Symbols.java.html dprogs/SynchBfsTree.java.html dprogs/SynchLinker.java.html dprogs/Synchronizer.java.html dprogs/TermDetector.java.html dprogs/TermShortestPath.java.html dprogs/TermTester.java.html dprogs/TermToken.java.html dprogs/Topology.java.html dprogs/TotalChat.java.html dprogs/Tree.java.html dprogs/TwoPhaseCoord.java.html dprogs/TwoPhaseParticipant.java.html dprogs/TwoPhaseTester.java.html dprogs/Util.java.html dprogs/VCLinker.java.html dprogs/VectorClock.java.html dprogs/AlphaSynch.java dprogs/BGATester.java dprogs/BetaSynch.java dprogs/CamCircToken.java dprogs/CamUser.java dprogs/Camera.java dprogs/CameraLinker.java dprogs/CameraTester.java dprogs/CausalLinker.java dprogs/CausalMessage.java dprogs/CentMutex.java dprogs/CentMutexTester.java dprogs/CentSensor.java dprogs/Chat.java dprogs/CircToken.java dprogs/Connector.java dprogs/Consensus.java dprogs/ConsensusTester.java dprogs/DSTerm.java dprogs/DatagramClient.java dprogs/DatagramServer.java dprogs/DinMutex.java dprogs/DirectClock.java dprogs/DistSensor.java dprogs/Election.java dprogs/ElectionTester.java dprogs/FuncUser.java dprogs/GlobalFunc.java dprogs/GlobalFuncTester.java dprogs/GlobalService.java dprogs/IntLinkedList.java dprogs/KingBGA.java dprogs/LamportClock.java dprogs/LamportMutex.java dprogs/Linker.java dprogs/ListenerThread.java dprogs/Lock.java dprogs/LockTester.java dprogs/Matrix.java dprogs/MatrixClock.java dprogs/Msg.java dprogs/MsgHandler.java dprogs/MsgList.java dprogs/Name.java dprogs/NameRmiClient.java dprogs/NameServer.java dprogs/NameService.java dprogs/NameServiceImpl.java dprogs/NameTable.java dprogs/PortAddr.java dprogs/Process.java dprogs/RAMutex.java dprogs/RecvCamera.java dprogs/RestartTask.java dprogs/RingLeader.java dprogs/SenderCamera.java dprogs/Sensor.java dprogs/SensorCircToken.java dprogs/SensorTester.java dprogs/SensorUser.java dprogs/SeqMessage.java dprogs/ShortestPath.java dprogs/SimpleSynch.java dprogs/SpanTree.java dprogs/SpanTreeTester.java dprogs/StableBottom.java dprogs/StableMutexTester.java dprogs/StableNormal.java dprogs/StableSpanNonroot.java dprogs/StableSpanRoot.java dprogs/StableTreeTester.java dprogs/Symbols.java dprogs/SynchBfsTree.java dprogs/SynchLinker.java dprogs/Synchronizer.java dprogs/SynchronizerTester.java dprogs/TermDetector.java dprogs/TermShortestPath.java dprogs/TermTester.java dprogs/TermToken.java dprogs/Topology.java dprogs/Tree.java dprogs/TwoPhaseCoord.java dprogs/TwoPhaseParticipant.java dprogs/TwoPhaseTester.java dprogs/Util.java dprogs/VCLinker.java dprogs/VectorClock.java dprogs/nLockTester.java dprogs/overview-tree.html dprogs/index-all.html dprogs/deprecated-list.html dprogs/allclasses-frame.html dprogs/index.html dprogs/packages.html dprogs/AlphaSynch.html dprogs/BetaSynch.html dprogs/BGATester.html dprogs/CamCircToken.html dprogs/Camera.html dprogs/CameraLinker.html dprogs/CameraTester.html dprogs/CamUser.html dprogs/CausalLinker.html dprogs/CausalMessage.html dprogs/CentMutex.html dprogs/CentMutexTester.html dprogs/CentSensor.html dprogs/Chat.html dprogs/CircToken.html dprogs/Connector.html dprogs/Consensus.html dprogs/ConsensusTester.html dprogs/DatagramClient.html dprogs/DatagramServer.html dprogs/DinMutex.html dprogs/DirectClock.html dprogs/DistSensor.html dprogs/DrinkMutex.html dprogs/DSTerm.html dprogs/Election.html dprogs/ElectionTester.html dprogs/FuncUser.html dprogs/GlobalFunc.html dprogs/GlobalFuncTester.html dprogs/GlobalService.html dprogs/IntLinkedList.html dprogs/KingBGA.html dprogs/LamportClock.html dprogs/LamportMutex.html dprogs/Linker.html dprogs/ListenerThread.html dprogs/Lock.html dprogs/LockTester.html dprogs/Matrix.html dprogs/MatrixClock.html dprogs/Msg.html dprogs/MsgHandler.html dprogs/MsgList.html dprogs/Name.html dprogs/NameRmiClient.html dprogs/NameServer.html dprogs/NameService.html dprogs/NameServiceImpl.html dprogs/NameTable.html dprogs/nLockTester.html dprogs/PortAddr.html dprogs/Process.html dprogs/RAMutex.html dprogs/RecvCamera.html dprogs/RestartTask.html dprogs/RingLeader.html dprogs/SenderCamera.html dprogs/Sensor.html dprogs/SensorCircToken.html dprogs/SensorTester.html dprogs/SensorUser.html dprogs/SeqMessage.html dprogs/ShortestPath.html dprogs/SimpleSynch.html dprogs/SpanTree.html dprogs/SpanTreeTester.html dprogs/StableBottom.html dprogs/StableMutexTester.html dprogs/StableNormal.html dprogs/StableSpanNonroot.html dprogs/StableSpanRoot.html dprogs/StableTreeTester.html dprogs/Symbols.html dprogs/SynchBfsTree.html dprogs/SynchLinker.html dprogs/Synchronizer.html dprogs/SynchronizerTester.html dprogs/TermDetector.html dprogs/TermShortestPath.html dprogs/TermTester.html dprogs/TermToken.html dprogs/Topology.html dprogs/Tree.html dprogs/TwoPhaseCoord.html dprogs/TwoPhaseParticipant.html dprogs/TwoPhaseTester.html dprogs/Util.html dprogs/VCLinker.html dprogs/VectorClock.html dprogs/serialized-form.html dprogs/package-list dprogs/help-doc.html dprogs/stylesheet.css dprogs/clocks-index.html dprogs/clocks-jindex.html dprogs/consensus-index.html dprogs/consensus-jindex.html dprogs/msgordering-index.html dprogs/msgordering-jindex.html dprogs/DrinkMutex.class dprogs/other-index.html dprogs/other-jindex.html dprogs/snapshots-index.html dprogs/snapshots-jindex.html dprogs/stabilization-index.html dprogs/stabilization-jindex.html dprogs/stablization-index.html dprogs/synch-index.html dprogs/synch-jindex.html dprogs/Process.class dprogs/MsgHandler.class dprogs/DrinkMutex.java dprogs/Lock.class dprogs/DinMutex.class dprogs/Linker.class dprogs/Msg.class dprogs/Connector.class dprogs/DrinkMutex.java.html dprogs/IntLinkedList.class dprogs/Util.class dprogs/mutex-index.html dprogs/Topology.class dprogs/Name.class dprogs/PortAddr.class dprogs/Symbols.class dprogs/mutex-jindex.html
public interface CamUser extends MsgHandler { void localState(); }dprogs/Camera.java.html 0000644 0002457 0000456 00000000627 10006037432 014643 0 ustar garg ecestaff
public interface Camera extends MsgHandler { void globalState(); }dprogs/CameraLinker.java.html 0000644 0002457 0000456 00000006301 10006037432 016003 0 ustar garg ecestaff
import java.util.*; import java.net.*; import java.io.*; public class CameraLinker extends Linker { static final int white = 0, red = 1; int seqNo[] = null; SenderCamera cam; public CameraLinker(String basename, int myId, int numProc) throws Exception { super(basename, myId, numProc); seqNo = new int[numProc]; for (int i = 0; i < numProc; i++) seqNo[i] = 0; } public void initCam(SenderCamera cam){ this.cam = cam; } public void sendMsg(int destId, String tag, String msg) { if ((tag.equals("marker")) || (tag.equals("ack"))) super.sendMsg(destId, tag, msg); else {// send seq numbers with app msgs seqNo[destId]++; Message m = new Message(myId, destId, tag, msg); if (cam.myColor == white) { cam.recordMessage(destId, new SeqMessage(m, seqNo[destId])); super.sendMsg(destId, "white", String.valueOf(seqNo[destId])+" " + m.toString() + " "); } else super.sendMsg(destId, "red", String.valueOf(seqNo[destId])+" " + m.toString() + " "); } } }dprogs/CameraTester.java.html 0000644 0002457 0000456 00000004564 10006037432 016036 0 ustar garg ecestaff
import java.util.Random; public class CameraTester { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Camera camera = null; CamCircToken sp = null; if (args[3].equals("RecvCamera")) { Linker comm = new Linker(baseName, myId, numProc); sp = new CamCircToken(comm, 0); camera = new RecvCamera(comm, sp); } if (args[3].equals("senderCamera")) { CameraLinker comm = new CameraLinker(args[0], myId, numProc); sp = new CamCircToken(comm, 0); camera = new SenderCamera(comm, sp); } sp.initiate(); // Util.mySleep(100); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, camera)).start(); if (myId == 0) camera.globalState(); } }dprogs/CausalLinker.java.html 0000644 0002457 0000456 00000011774 10006037432 016035 0 ustar garg ecestaff
import java.util.*; import java.net.*; import java.io.*; public class CausalLinker extends Linker { int M[][]; LinkedList deliveryQ = new LinkedList(); // deliverable messages LinkedList pendingQ = new LinkedList(); // messages with matrix public CausalLinker(String basename, int id, int numProc) throws Exception { super(basename, id, numProc); M = new int[N][N]; Matrix.setZero(M); } public synchronized void sendMsg(int destId, String tag, String msg){ M[myId][destId]++; super.sendMsg(destId, "matrix", Matrix.write(M)); super.sendMsg(destId, tag, msg); } public synchronized void multicast(IntLinkedList destIds, String tag, String msg) { for (int i=0; i<destIds.size(); i++) M[myId][destIds.getEntry(i)]++; for (int i=0; i<destIds.size(); i++) { int destId = destIds.getEntry(i); super.sendMsg(destId, "matrix", Matrix.write(M)); super.sendMsg(destId, tag, msg); } } boolean okayToRecv(int W[][], int srcId) { if (W[srcId][myId] > M[srcId][myId]+1) return false; for (int k = 0; k < N; k++) if ((k!=srcId) && (W[k][myId] > M[k][myId])) return false; return true; } synchronized void checkPendingQ() { ListIterator iter = pendingQ.listIterator(0); while (iter.hasNext()) { CausalMessage cm = (CausalMessage) iter.next(); if (okayToRecv(cm.getMatrix(), cm.getMessage().getSrcId())){ iter.remove(); deliveryQ.add(cm); } } } // polls the channel given by fromId to add to the pendingQ public Msg receiveMsg(int fromId) throws IOException { checkPendingQ(); while (deliveryQ.isEmpty()) { Msg matrix = super.receiveMsg(fromId);// matrix int [][]W = new int[N][N]; Matrix.read(matrix.getMessage(), W); Msg m1 = super.receiveMsg(fromId);//app message pendingQ.add(new CausalMessage(m1, N, W)); checkPendingQ(); } CausalMessage cm = (CausalMessage) deliveryQ.removeFirst(); Matrix.setMax(M, cm.getMatrix()); return cm.getMessage(); } }dprogs/CausalMessage.java.html 0000644 0002457 0000456 00000002006 10006037432 016161 0 ustar garg ecestaff
public class CausalMessage { Message m; int N; int W[][]; public CausalMessage(Message m, int N, int matrix[][]) { this.m = m; this.N = N; W = matrix; } public int[][] getMatrix() { return W; } public Message getMessage() { return m; } }dprogs/CentMutex.java.html 0000644 0002457 0000456 00000005646 10006037432 015375 0 ustar garg ecestaff
public class CentMutex extends Process implements Lock { // assumes that P_0 coordinates and does not request locks. boolean haveToken; final int leader = 0; IntLinkedList pendingQ = new IntLinkedList(); public CentMutex(Linker initComm) { super(initComm); haveToken = (myId == leader); } public synchronized void requestCS() { sendMsg(leader, "request"); while (!haveToken) myWait(); } public synchronized void releaseCS() { sendMsg(leader, "release"); haveToken = false; } public synchronized void handleMsg(Msg m, int src, String tag) { if (tag.equals("request")) { if (haveToken){ sendMsg(src, "okay"); haveToken = false; } else pendingQ.add(src); } else if (tag.equals("release")) { if (!pendingQ.isEmpty()) { int pid = pendingQ.removeHead(); sendMsg(pid, "okay"); } else haveToken = true; } else if (tag.equals("okay")) { haveToken = true; notify(); } } }dprogs/CentSensor.java.html 0000644 0002457 0000456 00000012331 10006037432 015531 0 ustar garg ecestaff
import java.util.*; public class CentSensor extends Process implements Runnable, Sensor { final static int red = 0, green = 1; LinkedList q[]; int cut[][], color[],gstate[]; boolean finished[]; SensorUser app; final int coordinator = Symbols.coordinator; public CentSensor(VCLinker initComm, SensorUser app) { super(initComm); cut = new int[N][N]; q = new LinkedList[N]; color = new int[N]; gstate = new int[N]; finished = new boolean[N]; for (int i = 0; i < N; i++) { q[i] = new LinkedList(); color[i] = red; finished[i] = false; } this.app = app; if (myId==coordinator) new Thread(this).start(); } public synchronized void localPredicateTrue(VectorClock vc){ if (myId==coordinator) handleMsg(new Message(0, 0, "trueVC", vc.toString()),0,"trueVC"); else ((VCLinker) comm).simpleSendMsg(coordinator, "trueVC", vc.toString()); } public synchronized void run() { int i = Util.searchArray(color, red); while (i != -1) { while (q[i].isEmpty() && !finished[i]){ myWait(); } if (finished[i]) { app.globalPredicateFalse(i); return; } cut[i] = (int[]) q[i].removeFirst(); paintState(i); i = Util.searchArray(color, red); } for (int j=0; j<N; j++) gstate[j] = cut[j][j]; app.globalPredicateTrue(gstate); } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("trueVC")) { int[] receiveTag = new int[N]; Util.readArray(m.getMessage(), receiveTag); q[source].add(receiveTag); notify(); } else if (tag.equals("finished")) { finished[source] = true; notify(); } } void paintState(int i) { color[i] = green; for (int j = 0; j < N; j++) if (color[j] == green) if (Util.lessThan(cut[i], cut[j])) color[i] = red; else if (Util.lessThan(cut[j], cut[i])) color[j] = red; } }dprogs/Chat.java.html 0000644 0002457 0000456 00000011314 10006037432 014325 0 ustar garg ecestaff
import java.io.*; import java.util.*; public class Chat extends Process { public Chat(Linker initComm) { super(initComm); } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("chat")) { System.out.println("Message from " + source +":"); System.out.println(m.getMessage()); } } public String getUserInput(BufferedReader din) throws Exception { System.out.println("Please type your message in a single line:"); String chatMsg = din.readLine(); return chatMsg; } public IntLinkedList getDest(BufferedReader din) throws Exception { System.out.println("Type in destination pids with -1 at end:"); IntLinkedList destIds = new IntLinkedList(); //dest for msg StringTokenizer st = new StringTokenizer(din.readLine()); while (st.hasMoreTokens()) { int pid = Integer.parseInt(st.nextToken()); if (pid == -1) break; else destIds.add(pid); } return destIds; } public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm=null; if (args[3].equals("simple")) comm = new Linker(baseName, myId, numProc); else if (args[3].equals("causal")) comm = new CausalLinker(baseName, myId, numProc); else if (args[3].equals("synch")) comm = new SynchLinker(baseName, myId, numProc); Chat c = new Chat(comm); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, c)).start(); BufferedReader din = new BufferedReader( new InputStreamReader(System.in)); while (true) { String chatMsg = c.getUserInput(din); if (chatMsg.equals("quit")) break; IntLinkedList destIds = c.getDest(din); comm.multicast(destIds, "chat", chatMsg); } } }dprogs/CircToken.java.html 0000644 0002457 0000456 00000005372 10006037432 015336 0 ustar garg ecestaff
import java.util.Timer; public class CircToken extends Process implements Lock { boolean haveToken; boolean wantCS = false; public CircToken(Linker initComm, int coordinator) { super(initComm); haveToken = (myId == coordinator); } public synchronized void initiate() { if (haveToken) sendToken(); } public synchronized void requestCS() { wantCS = true; while (!haveToken) myWait(); } public synchronized void releaseCS() { wantCS = false; sendToken(); } void sendToken() { if (haveToken && !wantCS) { int next = (myId + 1) % N; Util.println("Process " + myId + "has sent the token"); sendMsg(next, "token"); haveToken = false; } } public synchronized void handleMsg(Msg m, int src, String tag) { if (tag.equals("token")) { haveToken = true; if (wantCS) notify(); else { Util.mySleep(1000); sendToken(); } } } }dprogs/Connector.java.html 0000644 0002457 0000456 00000011076 10006037432 015405 0 ustar garg ecestaff
import java.util.*; import java.net.*; import java.io.*; public class Connector { ServerSocket listener; Socket [] link; public void Connect(String basename, int myId, int numProc, BufferedReader[] dataIn, PrintWriter[] dataOut) throws Exception { Name myNameclient = new Name(); link = new Socket[numProc];/* Get as many sockets as # of processes */ int localport = getLocalPort(myId);/* create a serverSocket for myself */ listener = new ServerSocket(localport); /* register in the name server */ myNameclient.insertName(basename + myId, (InetAddress.getLocalHost()).getHostName(), localport); /* accept connections from all the smaller processes */ for (int i = 0; i < myId; i++) { Socket s = listener.accept(); BufferedReader dIn = new BufferedReader( new InputStreamReader(s.getInputStream())); String getline = dIn.readLine(); StringTokenizer st = new StringTokenizer(getline); int hisId = Integer.parseInt(st.nextToken()); int destId = Integer.parseInt(st.nextToken()); String tag = st.nextToken(); if (tag.equals("hello")) { link[hisId] = s; dataIn[hisId] = dIn; dataOut[hisId] = new PrintWriter(s.getOutputStream()); } } /* contact all the bigger processes */ for (int i = myId + 1; i < numProc; i++) { PortAddr addr; do { addr = myNameclient.searchName(basename + i); Thread.sleep(100); } while (addr.getportnum() == -1); link[i] = new Socket(addr.gethostname(), addr.getportnum()); dataOut[i] = new PrintWriter(link[i].getOutputStream()); dataIn[i] = new BufferedReader(new InputStreamReader(link[i].getInputStream())); /* send a hello message to P_i */ dataOut[i].println(myId + " " + i + " " + "hello" + " " + "null"); dataOut[i].flush(); } } int getLocalPort(int id) { return Symbols.ServerPort + 10 + id; } public void closeSockets(){ try { listener.close(); for (int i=0;i<link.length; i++) link[i].close(); } catch (Exception e) {System.err.println(e);} } }dprogs/Consensus.java.html 0000644 0002457 0000456 00000005666 10006037432 015443 0 ustar garg ecestaff
import java.util.*; public class Consensus extends Process { int myValue; int f; // maximum number of faults boolean changed = true; boolean hasProposed = false; public Consensus(Linker initComm, int f) { super(initComm); this.f = f; } public synchronized void propose(int value) { myValue = value; hasProposed = true; notify(); } public int decide() { for (int k = 0; k <= f; k++) { // f+1 rounds synchronized (this) { if (changed) broadcastMsg("proposal", myValue); } // sleep enough to receive messages for this round Util.mySleep(Symbols.roundTime); } synchronized (this) { return myValue; } } public synchronized void handleMsg(Msg m, int src, String tag) { while (!hasProposed) myWait(); if (tag.equals("proposal")) { int value = m.getMessageInt(); if (value < myValue) { myValue = value; changed = true; } else changed = false; } } }dprogs/ConsensusTester.java.html 0000644 0002457 0000456 00000002673 10006037432 016625 0 ustar garg ecestaff
public class ConsensusTester { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm = new Linker(baseName, myId, numProc); Consensus sp = new Consensus(comm, 3); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, sp)).start(); sp.propose(myId); System.out.println("The value decided upon is " + sp.decide()); } }dprogs/DSTerm.java.html 0000644 0002457 0000456 00000006424 10006037432 014612 0 ustar garg ecestaff
public class DSTerm extends Process implements TermDetector { final static int passive = 0, active = 1; int state = passive; int D = 0; int parent = -1; boolean envtFlag; public DSTerm(Linker initComm) { super(initComm); envtFlag = (myId == Symbols.coordinator); } public synchronized void initiate() { } public synchronized void handleMsg(Msg m, int src, String tag) { if (tag.equals("signal")) { D = D - 1; if (D == 0) { if (envtFlag) System.out.println("Termination Detected"); else if (state == passive) { sendMsg(parent, "signal"); parent = -1; } } } else { // application message state = active; if ((parent == -1) && !envtFlag) { parent = src; } else sendMsg(src, "signal"); } } public synchronized void sendAction() { D = D + 1; } public synchronized void turnPassive() { state = passive; if ((D == 0) && (parent != -1)) { sendMsg(parent, "signal"); parent = -1; } } }dprogs/DatagramClient.java.html 0000644 0002457 0000456 00000006253 10006037432 016333 0 ustar garg ecestaff
import java.net.*; import java.io.*; public class DatagramClient { public static void main(String[] args) { String hostname; int port = 2018; int len = 1024; DatagramPacket sPacket, rPacket; if (args.length > 0) hostname = args[0]; else hostname = "localhost"; try { InetAddress ia = InetAddress.getByName(hostname); DatagramSocket datasocket = new DatagramSocket(); BufferedReader stdinp = new BufferedReader( new InputStreamReader(System.in)); while (true) { try { String echoline = stdinp.readLine(); if (echoline.equals("done")) break; byte[] buffer = new byte[echoline.length()]; buffer = echoline.getBytes(); sPacket = new DatagramPacket(buffer, buffer.length, ia, port); datasocket.send(sPacket); byte[] rbuffer = new byte[len]; rPacket = new DatagramPacket(rbuffer, rbuffer.length); datasocket.receive(rPacket); String retstring = new String(rPacket.getData()); System.out.println(retstring); } catch (IOException e) { System.err.println(e); } } // while } catch (UnknownHostException e) { System.err.println(e); } catch (SocketException se) { System.err.println(se); } } // end main }dprogs/DatagramServer.java.html 0000644 0002457 0000456 00000003764 10006037432 016367 0 ustar garg ecestaff
import java.net.*; import java.io.*; public class DatagramServer { public static void main(String[] args) { DatagramPacket datapacket, returnpacket; int port = 2018; int len = 1024; try { DatagramSocket datasocket = new DatagramSocket(port); byte[] buf = new byte[len]; datapacket = new DatagramPacket(buf, buf.length); while (true) { try { datasocket.receive(datapacket); returnpacket = new DatagramPacket( datapacket.getData(), datapacket.getLength(), datapacket.getAddress(), datapacket.getPort()); datasocket.send(returnpacket); } catch (IOException e) { System.err.println(e); } } } catch (SocketException se) { System.err.println(se); } } }dprogs/DinMutex.java.html 0000644 0002457 0000456 00000011733 10006037432 015210 0 ustar garg ecestaff
public class DinMutex extends Process implements Lock { private static final int thinking = 0, hungry = 1, eating = 2; boolean fork[] = null, dirty[] = null, request[] = null; int myState = thinking; public DinMutex(Linker initComm) { super(initComm); fork = new boolean[N]; dirty = new boolean[N]; request = new boolean[N]; for (int i = 0; i < N; i++) { if ((myId > i) && (isNeighbor(i))) { fork[i] = false; request[i] = true; } else { fork[i] = true; request[i] = false; } dirty[i] = true; } } public synchronized void requestCS() { myState = hungry; if (haveForks()) myState = eating; else for (int i = 0; i < N; i++) if (request[i] && !fork[i]) { sendMsg(i, "Request"); request[i] = false; } while (myState != eating) myWait(); } public synchronized void releaseCS() { myState = thinking; for (int i = 0; i < N; i++) { dirty[i] = true; if (request[i]) { sendMsg(i, "Fork"); fork[i] = false; } } } boolean haveForks() { for (int i = 0; i < N; i++) if (!fork[i]) return false; return true; } public synchronized void handleMsg(Msg m, int src, String tag) { if (tag.equals("Request")) { request[src] = true; if ((myState != eating) && fork[src] && dirty[src]) { sendMsg(src, "Fork"); fork[src] = false; if (myState == hungry){ sendMsg(src, "Request"); request[src] = false; } } } else if (tag.equals("Fork")) { fork[src] = true; dirty[src] = false; if (haveForks()) { myState = eating; notify(); } } } }dprogs/DirectClock.java.html 0000644 0002457 0000456 00000003525 10006037432 015641 0 ustar garg ecestaff
public class DirectClock { public int[] clock; int myId; public DirectClock(int numProc, int id) { myId = id; clock = new int[numProc]; for (int i = 0; i < numProc; i++) clock[i] = 0; clock[myId] = 1; } public int getValue(int i) { return clock[i]; } public void tick() { clock[myId]++; } public void sendAction() { // sentValue = clock[myId]; tick(); } public void receiveAction(int sender, int sentValue) { clock[sender] = Util.max(clock[sender], sentValue); clock[myId] = Util.max(clock[myId], sentValue) + 1; } }dprogs/DistSensor.java.html 0000644 0002457 0000456 00000012134 10006037432 015544 0 ustar garg ecestaff
import java.util.*; public class DistSensor extends Process implements Runnable,Sensor { final static int red = 0, green = 1; int candidate[], color[],G[]; boolean finished = false, haveToken = false; LinkedList q = new LinkedList(); SensorUser app; public DistSensor(VCLinker initComm, SensorUser app) { super(initComm); this.app = app; candidate = new int[N]; color = new int[N]; G = new int[N]; for (int j=0; j<N; j++) { color[j] = red; G[j] = 0;} if (myId==Symbols.coordinator) haveToken=true; new Thread(this).start(); } public synchronized void run(){ while (!finished) { while (!haveToken) myWait(); handleToken(); } } public synchronized void handleToken() { while (color[myId] == red) { while (q.isEmpty() && !finished) myWait(); if (q.isEmpty() && finished) { app.globalPredicateFalse(myId); return; } candidate = (int[]) q.removeFirst(); if (candidate[myId] > G[myId]) { G[myId] = candidate[myId]; color[myId] = green; } } for (int j = 0; j < N; j++) if ((j != myId) && (candidate[j] >= G[j])) { G[j] = candidate[j]; color[j] = red; } int j = Util.searchArray(color, red); if (j != -1) sendToken(j); else { app.globalPredicateTrue(G); finished = true; } } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("TokenG")) Util.readArray(m.getMessage(), G); else if (tag.equals("Tokencolor")) { Util.readArray(m.getMessage(), color); haveToken = true; notifyAll(); } else if (tag.equals("finished")) finished = true; } void sendToken(int j) { ((VCLinker) comm).simpleSendMsg(j, "TokenG", Util.writeArray(G)); ((VCLinker) comm).simpleSendMsg(j,"Tokencolor",Util.writeArray(color)); haveToken = false; } public synchronized void localPredicateTrue(VectorClock vc) { q.add(vc.v); notifyAll(); } }dprogs/Election.java.html 0000644 0002457 0000456 00000001025 10006037432 015206 0 ustar garg ecestaff
public interface Election extends MsgHandler { void startElection(); int getLeader();//blocks till the leader is known }dprogs/FuncUser.java.html 0000644 0002457 0000456 00000000731 10006037432 015201 0 ustar garg ecestaff
public interface FuncUser { public int func(int x, int y); }dprogs/GlobalFunc.java.html 0000644 0002457 0000456 00000007632 10006037432 015472 0 ustar garg ecestaff
import java.util.*; public class GlobalFunc extends Process implements GlobalService { FuncUser prog; SpanTree tree = null; IntLinkedList pending = new IntLinkedList(); int myValue; int answer; boolean answerRecvd; boolean pendingSet = false; public GlobalFunc(Linker initComm, boolean isRoot) { super(initComm); tree = new SpanTree(comm, isRoot); } public void initialize(int myValue, FuncUser prog) { this.myValue = myValue; this.prog = prog; tree.waitForDone(); Util.println(myId + ":" + tree.children.toString()); } public synchronized int computeGlobal() { pending.addAll(tree.children); pendingSet = true; notifyAll(); while (!pending.isEmpty()) myWait(); if (tree.parent == myId) { // root node answer = myValue; } else { //non-root node sendMsg(tree.parent, "subTreeVal", myValue); answerRecvd = false; while (!answerRecvd) myWait(); } sendChildren(answer); return answer; } void sendChildren(int value) { ListIterator t = tree.children.listIterator(0); while (t.hasNext()) { Integer child = (Integer) t.next(); sendMsg(child.intValue(), "globalFunc", value); } } public synchronized void handleMsg(Message m, int source, String tag) { tree.handleMsg(m,source,tag); if (tag.equals("subTreeVal")) { while (!pendingSet) myWait(); pending.remove(new Integer(source)); myValue = prog.func(myValue, m.getMessageInt()); if (pending.isEmpty()) notifyAll(); } else if (tag.equals("globalFunc")) { answer = m.getMessageInt(); answerRecvd = true; notifyAll(); } } }dprogs/GlobalFuncTester.java.html 0000644 0002457 0000456 00000003771 10006037432 016661 0 ustar garg ecestaff
public class GlobalFuncTester implements FuncUser { public int func(int x, int y) { return x + y; } public static void main(String[] args) throws Exception { int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm = new Linker(args[0], myId, numProc); GlobalFunc g = new GlobalFunc(comm, (myId == 0)); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, g)).start(); int myValue = Integer.parseInt(args[3]); GlobalFuncTester h = new GlobalFuncTester(); g.initialize(myValue, h); int globalSum = g.computeGlobal(); System.out.println("The global sum is " + globalSum); } }dprogs/GlobalService.java.html 0000644 0002457 0000456 00000001012 10006037432 016161 0 ustar garg ecestaff
public interface GlobalService extends MsgHandler { public int computeGlobal(int x, FuncUser prog); }dprogs/IntLinkedList.java.html 0000644 0002457 0000456 00000003011 10006037432 016156 0 ustar garg ecestaff
import java.util.LinkedList; public class IntLinkedList extends LinkedList { public void add(int i) { super.add(new Integer(i)); } public boolean contains(int i) { return super.contains(new Integer(i)); } public int removeHead() { Integer j = (Integer) super.removeFirst(); return j.intValue(); } public int getEntry(int index) { Integer j = (Integer) super.get(index); return j.intValue(); } }dprogs/KingBGA.java.html 0000644 0002457 0000456 00000011070 10006037432 014647 0 ustar garg ecestaff
import java.util.*; public class KingBGA extends Process { final static int defaultValue = 0; int f; // maximum number of faults int V[]; // set of values known int kingValue, myValue; public KingBGA(Linker initComm, int f) { super(initComm); this.f = f; V = new int[N]; } public synchronized void propose(int val) { for (int i = 0; i < N; i++) V[i] = defaultValue; V[myId] = val; } public int decide() { for (int k = 0; k <= f; k++) { // f+1 rounds broadcastMsg("phase1", V[myId]); Util.mySleep(Symbols.roundTime); synchronized (this) { myValue = getMajority(V); if (k == myId) broadcastMsg("king", myValue); } Util.mySleep(Symbols.roundTime); synchronized (this) { if (numCopies(V, myValue) > N / 2 + f) V[myId] = myValue; else V[myId] = kingValue; } } return V[myId]; } public synchronized void handleMsg(Msg m, int src, String tag) { if (tag.equals("phase1")) { V[src] = m.getMessageInt(); } else if (tag.equals("king")) { kingValue = m.getMessageInt(); } } int getMajority(int V[]) { if (numCopies(V, 0) > N / 2) return 0; else if (numCopies(V, 1) > N / 2) return 1; else return defaultValue; } int numCopies(int V[], int v) { int count = 0; for (int i = 0; i < V.length; i++) if (V[i] == v) count++; return count; } }dprogs/LamportClock.java.html 0000644 0002457 0000456 00000002464 10006037432 016046 0 ustar garg ecestaff
public class LamportClock { int c; public LamportClock() { c = 1; } public int getValue() { return c; } public void tick() { // on internal actions c = c + 1; } public void sendAction() { // include c in message c = c + 1; } public void receiveAction(int src, int sentValue) { c = Util.max(c, sentValue) + 1; } }dprogs/LamportMutex.java.html 0000644 0002457 0000456 00000007310 10006037432 016110 0 ustar garg ecestaff
public class LamportMutex extends Process implements Lock { DirectClock v; int[] q; // request queue public LamportMutex(Linker initComm) { super(initComm); v = new DirectClock(N, myId); q = new int[N]; for (int j = 0; j < N; j++) q[j] = Symbols.Infinity; } public synchronized void requestCS() { v.tick(); q[myId] = v.getValue(myId); broadcastMsg("request", q[myId]); while (!okayCS()) myWait(); } public synchronized void releaseCS() { q[myId] = Symbols.Infinity; broadcastMsg("release", v.getValue(myId)); } boolean okayCS() { for (int j = 0; j < N; j++){ if (isGreater(q[myId], myId, q[j], j)) return false; if (isGreater(q[myId], myId, v.getValue(j), j)) return false; } return true; } boolean isGreater(int entry1, int pid1, int entry2, int pid2) { if (entry2 == Symbols.Infinity) return false; return ((entry1 > entry2) || ((entry1 == entry2) && (pid1 > pid2))); } public synchronized void handleMsg(Msg m, int src, String tag) { int timeStamp = m.getMessageInt(); v.receiveAction(src, timeStamp); if (tag.equals("request")) { q[src] = timeStamp; sendMsg(src, "ack", v.getValue(myId)); } else if (tag.equals("release")) q[src] = Symbols.Infinity; notify(); // okayCS() may be true now } }dprogs/Linker.java.html 0000644 0002457 0000456 00000010251 10006037432 014671 0 ustar garg ecestaff
import java.util.*; import java.io.*; public class Linker { PrintWriter[] dataOut; BufferedReader[] dataIn; BufferedReader dIn; int myId, N; Connector connector; public IntLinkedList neighbors = new IntLinkedList(); public Linker(String basename, int id, int numProc) throws Exception { myId = id; N = numProc; dataIn = new BufferedReader[numProc]; dataOut = new PrintWriter[numProc]; Topology.readNeighbors(myId, N, neighbors); connector = new Connector(); connector.Connect(basename, myId, numProc, dataIn, dataOut); } public void sendMsg(int destId, String tag, String msg) { Util.println("Sending msg to " + destId + ":" +tag + " " + msg); dataOut[destId].println(myId + " " + destId + " " + tag + " " + msg + "#"); dataOut[destId].flush(); } public void sendMsg(int destId, String tag) { sendMsg(destId, tag, " 0 "); } public void multicast(IntLinkedList destIds, String tag, String msg) { for (int i=0; i<destIds.size(); i++) { sendMsg(destIds.getEntry(i), tag, msg); } } public Message receiveMsg(int fromId) throws IOException { String getline = dataIn[fromId].readLine(); Util.println(" received message " + getline); StringTokenizer st = new StringTokenizer(getline); int srcId = Integer.parseInt(st.nextToken()); int destId = Integer.parseInt(st.nextToken()); String tag = st.nextToken(); String msg = st.nextToken("#"); return new Message(srcId, destId, tag, msg); } public int getMyId() { return myId; } public int getNumProc() { return N; } public void close() {connector.closeSockets();} public static void main(String[] args) throws Exception { new Linker(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2])); } }dprogs/ListenerThread.java.html 0000644 0002457 0000456 00000002370 10006037432 016365 0 ustar garg ecestaff
import java.io.*; public class ListenerThread extends Thread { int channel; MsgHandler process; public ListenerThread(int channel, MsgHandler process) { this.channel = channel; this.process = process; } public void run() { while (true) { try { Message m = process.receiveMsg(channel); process.handleMsg(m, m.getSrcId(), m.getTag()); } catch (IOException e) { System.err.println(e); } } } }dprogs/Lock.java.html 0000644 0002457 0000456 00000001113 10006037432 014332 0 ustar garg ecestaff
public interface Lock extends MsgHandler { public void requestCS(); //may block public void releaseCS(); }dprogs/LockTester.java.html 0000644 0002457 0000456 00000006240 10006037432 015527 0 ustar garg ecestaff
public class LockTester { public static void main(String[] args) throws Exception { Linker comm = null; try { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); comm = new Linker(baseName, myId, numProc); Lock lock = null; if (args[3].equals("Lamport")) lock = new LamportMutex(comm); if (args[3].equals("RicartAgrawala")) lock = new RAMutex(comm); if (args[3].equals("DiningPhil")) lock = new DinMutex(comm); if (args[3].equals("CircToken")) lock = new CircToken(comm,0); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, (MsgHandler)lock)).start(); while (true) { System.out.println(myId + " is not in CS"); Util.mySleep(2000); lock.requestCS(); Util.mySleep(2000); System.out.println(myId + " is in CS *****"); lock.releaseCS(); } } catch (InterruptedException e) { if (comm != null) comm.close(); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } }dprogs/Matrix.java.html 0000644 0002457 0000456 00000005272 10006037432 014720 0 ustar garg ecestaff
import java.util.*; public class Matrix { public static String write(int A[][]){ StringBuffer s = new StringBuffer(); for (int j = 0; j < A.length; j++) s.append(Util.writeArray(A[j]) + " "); return new String(s.toString()); } public static void read(String s, int A[][]) { StringTokenizer st = new StringTokenizer(s); for (int i = 0; i < A.length; i++) for (int j = 0; j < A[i].length; j++) A[i][j] = Integer.parseInt(st.nextToken()); } public static void setZero(int A[][]) { for (int i = 0; i < A.length; i++) for (int j = 0; j < A[i].length; j++) A[i][j] = 0; } public static void setMax(int A[][], int B[][]) { for (int i = 0; i < A.length; i++) for (int j = 0; j < A[i].length; j++) A[i][j] = Util.max(A[i][j], B[i][j]); } }dprogs/MatrixClock.java.html 0000644 0002457 0000456 00000005316 10006037432 015673 0 ustar garg ecestaff
public class MatrixClock { int[][] M; int myId; int N; public MatrixClock(int numProc, int id) { myId = id; N = numProc; M = new int[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) M[i][j] = 0; M[myId][myId] = 1; } public void tick() { M[myId][myId]++; } public void sendAction() { //include the matrix in the message M[myId][myId]++; } public void receiveAction(int[][] W, int srcId) { // component-wise maximum of matrices for (int i = 0; i < N; i++) if (i != myId) { for (int j = 0; j < N; j++) M[i][j] = Util.max(M[i][j], W[i][j]); } // update the vector for this process for (int j = 0; j < N; j++) M[myId][j] = Util.max(M[myId][j], W[srcId][j]); M[myId][myId]++; } public int getValue(int i, int j) { return M[i][j]; } }dprogs/Message.java.html 0000644 0002457 0000456 00000005213 10006037432 015033 0 ustar garg ecestaff
import java.util.*; public class Message { int srcId, destId; String tag; String msg; public Message(int s, int t, String msgType, String buf) { this.srcId = s; destId = t; tag = msgType; msg = buf; } public int getSrcId() { return srcId; } public int getDestId() { return destId; } public String getTag() { return tag; } public String getMessage() { return msg; } public int getMessageInt() { Util.println("msg is:" + msg); StringTokenizer st = new StringTokenizer(msg); return Integer.parseInt(st.nextToken()); } public static Message parseMsg(StringTokenizer st){ int srcId = Integer.parseInt(st.nextToken()); int destId = Integer.parseInt(st.nextToken()); String tag = st.nextToken(); String msg = st.nextToken("#"); return new Message(srcId, destId, tag, msg); } public String toString(){ String s = String.valueOf(srcId)+" " + String.valueOf(destId)+ " " + tag + " " + msg + "#"; return s; } }dprogs/MsgHandler.java.html 0000644 0002457 0000456 00000001261 10006037432 015472 0 ustar garg ecestaff
import java.io.*; public interface MsgHandler { public void handleMsg(Message m, int srcsId, String tag); public Message receiveMsg(int fromId) throws IOException; }dprogs/MsgList.java.html 0000644 0002457 0000456 00000003306 10006037432 015032 0 ustar garg ecestaff
import java.util.*; public class MsgList extends LinkedList { public void insert(SeqMessage sm) { int ts = sm.getSeqNo(); ListIterator iter = super.listIterator(0); while (iter.hasNext()) { int t = ((SeqMessage) iter.next()).getSeqNo(); if (ts <= t) break; } iter.add(sm); // error: add before } public Message removeM(int seqNo) { SeqMessage sm; ListIterator iter = super.listIterator(0); while (iter.hasNext()) { sm = (SeqMessage) iter.next(); if (sm.getSeqNo() == seqNo) { iter.remove(); return sm.getMessage(); } } return null; } }dprogs/Name.java.html 0000644 0002457 0000456 00000006100 10006037432 014323 0 ustar garg ecestaff
import java.lang.*; import java.util.*; import java.net.*; import java.io.*; public class Name { BufferedReader din; PrintStream pout; public void getSocket() throws IOException { Socket server = new Socket(Symbols.nameServer, Symbols.ServerPort); din = new BufferedReader(new InputStreamReader(server.getInputStream())); pout = new PrintStream(server.getOutputStream()); } public int insertName(String name, String hname, int portnum) throws IOException { getSocket(); pout.println("insert " + name + " " + hname + " " + portnum); pout.flush(); return Integer.parseInt(din.readLine()); } public PortAddr searchName(String name) throws IOException { getSocket(); pout.println("search " + name); pout.flush(); String result = din.readLine(); StringTokenizer st = new StringTokenizer(result); int portnum = Integer.parseInt(st.nextToken()); String hname = st.nextToken(); return new PortAddr(hname, portnum); } public static void main(String[] args) { Name myClient = new Name(); try { myClient.insertName("hello1", "birch.ece.utexas.edu", 1000); PortAddr pa = myClient.searchName("hello1"); System.out.println(pa.gethostname() + ":" + pa.getportnum()); } catch (Exception e) { System.err.println("Server aborted:" + e); } } }dprogs/NameRmiClient.java.html 0000644 0002457 0000456 00000002512 10006037432 016135 0 ustar garg ecestaff
import java.rmi.*; public class NameRmiClient { public static void main(String args[]) { try { NameService r = (NameService) Naming.lookup("rmi://linux02/MyNameServer"); int i = r.insert("p1", "tick.ece", 2058); int j = r.search("p1"); if (j != -1) System.out.println(r.getHostName(j) + ":" + r.getPort(j)); } catch (Exception e) { System.out.println(e); } } }dprogs/NameServer.java.html 0000644 0002457 0000456 00000006707 10006037432 015527 0 ustar garg ecestaff
import java.net.*; import java.io.*; import java.util.*; public class NameServer { NameTable table; public NameServer() { table = new NameTable(); } void handleclient(Socket theClient) { try { BufferedReader din = new BufferedReader (new InputStreamReader(theClient.getInputStream())); PrintWriter pout = new PrintWriter(theClient.getOutputStream()); String getline = din.readLine(); StringTokenizer st = new StringTokenizer(getline); String tag = st.nextToken(); if (tag.equals("search")) { int index = table.search(st.nextToken()); if (index == -1) // not found pout.println(-1 + " " + "nullhost"); else pout.println(table.getPort(index) + " " + table.getHostName(index)); } else if (tag.equals("insert")) { String name = st.nextToken(); String hostName = st.nextToken(); int port = Integer.parseInt(st.nextToken()); int retValue = table.insert(name, hostName, port); pout.println(retValue); } pout.flush(); } catch (IOException e) { System.err.println(e); } } public static void main(String[] args) { NameServer ns = new NameServer(); System.out.println("NameServer started:"); try { ServerSocket listener = new ServerSocket(Symbols.ServerPort); while (true) { Socket aClient = listener.accept(); ns.handleclient(aClient); aClient.close(); } } catch (IOException e) { System.err.println("Server aborted:" + e); } } }dprogs/NameService.java.html 0000644 0002457 0000456 00000002250 10006037432 015646 0 ustar garg ecestaff
import java.rmi.*; public interface NameService extends Remote { public int search(String s) throws RemoteException; public int insert(String s, String hostName, int portNumber) throws RemoteException; public int getPort(int index) throws RemoteException; public String getHostName(int index) throws RemoteException; }dprogs/NameServiceImpl.java.html 0000644 0002457 0000456 00000010120 10006037432 016463 0 ustar garg ecestaff
import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class NameServiceImpl extends UnicastRemoteObject implements NameService { final int maxSize = 100; private String[] names = new String[maxSize]; private String[] hosts = new String[maxSize]; private int[] ports = new int[maxSize]; private int dirsize = 0; public NameServiceImpl() throws RemoteException { } public int search(String s) throws RemoteException { for (int i = 0; i < dirsize; i++) if (names[i].equals(s)) return i; return -1; } public int insert(String s, String hostName, int portNumber) throws RemoteException { int oldIndex = search(s); // is it already there if ((oldIndex == -1) && (dirsize < maxSize)) { names[dirsize] = s; hosts[dirsize] = hostName; ports[dirsize] = portNumber; dirsize++; return 1; } else return 0; } public int getPort(int index) throws RemoteException { return ports[index]; } public String getHostName(int index) throws RemoteException { return hosts[index]; } public static void main(String args[]) { // create security manager System.setSecurityManager(new RMISecurityManager()); try { NameServiceImpl obj = new NameServiceImpl(); Naming.rebind("MyNameServer", obj); System.out.println("MyNameServer bound in registry"); } catch (Exception e) { System.out.println("NameServiceImpl err: " + e.getMessage()); } } }dprogs/NameTable.java.html 0000644 0002457 0000456 00000004715 10006037432 015305 0 ustar garg ecestaff
import java.util.*; public class NameTable { final int maxSize = 100; private String[] names = new String[maxSize]; private String[] hosts = new String[maxSize]; private int[] ports = new int[maxSize]; private int dirsize = 0; int search(String s) { for (int i = 0; i < dirsize; i++) if (names[i].equals(s)) return i; return -1; } int insert(String s, String hostName, int portNumber) { int oldIndex = search(s); // is it already there if (oldIndex == -1) { names[dirsize] = s; hosts[dirsize] = hostName; ports[dirsize] = portNumber; dirsize++; return 1; } else return 0; } int getPort(int index) { return ports[index]; } String getHostName(int index) { return hosts[index]; } }dprogs/PortAddr.java.html 0000644 0002457 0000456 00000001574 10006037432 015174 0 ustar garg ecestaff
public class PortAddr { String hostname; int portnum; public PortAddr(String s, int i) { hostname = new String(s); portnum = i; } public String gethostname() { return hostname; } public int getportnum() { return portnum; } }dprogs/Process.java.html 0000644 0002457 0000456 00000010221 10006037432 015060 0 ustar garg ecestaff
import java.io.*; import java.lang.*; public class Process implements MsgHandler { int N, myId; Linker comm; public Process(Linker initComm) { comm = initComm; myId = comm.getMyId(); N = comm.getNumProc(); } public synchronized void handleMsg(Message m, int source, String tag) { } public void sendMsg(int destId, String tag, String msg) { Util.println("Sending msg to " + destId + ":" +tag + " " + msg); comm.sendMsg(destId, tag, msg); } public void sendMsg(int destId, String tag, int msg) { sendMsg(destId, tag, String.valueOf(msg)+" "); } public void sendMsg(int destId, String tag, int msg1, int msg2) { sendMsg(destId,tag,String.valueOf(msg1)+" "+String.valueOf(msg2)+" "); } public void sendMsg(int destId, String tag) { sendMsg(destId, tag, " 0 "); } public void broadcastMsg(String tag, int msg) { for (int i = 0; i < N; i++) if (i != myId) sendMsg(i, tag, msg); } public void sendToNeighbors(String tag, int msg) { comm.multicast(comm.neighbors, tag, String.valueOf(msg)+" "); } public boolean isNeighbor(int i) { if (comm.neighbors.contains(i)) return true; else return false; } public Message receiveMsg(int fromId) { try { return comm.receiveMsg(fromId); } catch (IOException e){ System.out.println(e); comm.close(); return null; } } public synchronized void myWait() { try { wait(); } catch (InterruptedException e) {System.err.println(e); } } }dprogs/RAMutex.java.html 0000644 0002457 0000456 00000006034 10006037432 014776 0 ustar garg ecestaff
import java.util.*; public class RAMutex extends Process implements Lock { int myts; LamportClock c = new LamportClock(); IntLinkedList pendingQ = new IntLinkedList(); int numOkay = 0; public RAMutex(Linker initComm) { super(initComm); myts = Symbols.Infinity; } public synchronized void requestCS() { c.tick(); myts = c.getValue(); broadcastMsg("request", myts); numOkay = 0; while (numOkay < N-1) myWait(); } public synchronized void releaseCS() { myts = Symbols.Infinity; while (!pendingQ.isEmpty()) { int pid = pendingQ.removeHead(); sendMsg(pid, "okay", c.getValue()); } } public synchronized void handleMsg(Msg m, int src, String tag) { int timeStamp = m.getMessageInt(); c.receiveAction(src, timeStamp); if (tag.equals("request")) { if ((myts == Symbols.Infinity) // not interested in CS || (timeStamp < myts) || ((timeStamp == myts) && (src < myId))) sendMsg(src, "okay", c.getValue()); else pendingQ.add(src); } else if (tag.equals("okay")) { numOkay++; if (numOkay == N - 1) notify(); // okayCS() may be true now } } }dprogs/RecvCamera.java.html 0000644 0002457 0000456 00000010100 10006037432 015446 0 ustar garg ecestaff
import java.util.*; public class RecvCamera extends Process implements Camera { static final int white = 0, red = 1; int myColor = white; boolean closed[]; CamUser app; LinkedList chan[] = null; public RecvCamera(Linker initComm, CamUser app) { super(initComm); closed = new boolean[N]; chan = new LinkedList[N]; for (int i = 0; i < N; i++) if (isNeighbor(i)) { closed[i] = false; chan[i] = new LinkedList(); } else closed[i] = true; this.app = app; } public synchronized void globalState() { myColor = red; app.localState(); // record local State; sendToNeighbors("marker", myId); // send Markers } public synchronized void handleMsg(Msg m, int src, String tag) { if (tag.equals("marker")) { if (myColor == white) globalState(); closed[src] = true; if (isDone()){ System.out.println("Channel State: Transit Messages "); for (int i = 0; i < N; i++) if (isNeighbor(i)) while (!chan[i].isEmpty()) System.out.println( ((Msg) chan[i].removeFirst()).toString()); } } else { // application message if ((myColor == red) && (!closed[src])) chan[src].add(m); app.handleMsg(m, src, tag); // give it to app } } boolean isDone() { if (myColor == white) return false; for (int i = 0; i < N; i++) if (!closed[i]) return false; return true; } }dprogs/RestartTask.java.html 0000644 0002457 0000456 00000001465 10006037432 015723 0 ustar garg ecestaff
import java.util.TimerTask; public class RestartTask extends TimerTask { MsgHandler app; public RestartTask(MsgHandler app) { this.app = app; } public void run() { app.handleMsg(null, 0, "restart"); } }dprogs/RingLeader.java.html 0000644 0002457 0000456 00000005722 10006037432 015470 0 ustar garg ecestaff
public class RingLeader extends Process implements Election { int number; int leaderId = -1; int next; boolean awake = false; public RingLeader(Linker initComm, int number) { super(initComm); this.number = number; next = (myId + 1) % N; } public synchronized int getLeader(){ while (leaderId == -1) myWait(); return leaderId; } public synchronized void handleMsg(Msg m, int src, String tag) { int j = m.getMessageInt(); // get the number if (tag.equals("election")) { if (j > number) sendMsg(next, "election", j); // forward the message else if (j == number) // I won! sendMsg(next, "leader", myId); else if ((j < number) && !awake) startElection(); } else if (tag.equals("leader")) { leaderId = j; notify(); if (j != myId) sendMsg(next, "leader", j); } } public synchronized void startElection() { awake = true; sendMsg(next, "election", number); } }dprogs/SenderCamera.java.html 0000644 0002457 0000456 00000011003 10006037432 015772 0 ustar garg ecestaff
import java.util.*; public class SenderCamera extends Process implements Camera { static final int white = 0, red = 1; public int myColor = white; CamUser app; boolean closed[]; MsgList outChan[] = null; public SenderCamera(CameraLinker initComm, CamUser app) { super(initComm); this.app = app; closed = new boolean[N]; outChan = new MsgList[N]; for (int i = 0; i < N; i++) if (isNeighbor(i)) { closed[i] = false; outChan[i] = new MsgList(); } else closed[i] = true; initComm.initCam(this); } public void globalState() { myColor = red; app.localState(); // record local State; sendToNeighbors("marker", myId); // send Markers } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("marker")) { if (myColor == white) globalState(); closed[source] = true; checkDone(); } else if (tag.equals("ack")) { int seqNo = m.getMessageInt(); outChan[source].removeM(seqNo); } else { // application message StringTokenizer st = new StringTokenizer(m.getMessage() + "#"); int seqNo = Integer.parseInt(st.nextToken()); Message appMsg = Message.parseMsg(st); if ((myColor==white)&& (tag.equals("white"))) sendMsg(source, "ack", seqNo); if ((myColor==white)&& (tag.equals("red"))) globalState(); app.handleMsg(appMsg, source, appMsg.getTag()); } } void checkDone() { boolean done = true; if (myColor == white) done = false; for (int i = 0; i < N; i++) if (closed[i] == false) done = false; } public void recordMessage(int destId, SeqMessage sm){ outChan[destId].add(sm); } }dprogs/Sensor.java.html 0000644 0002457 0000456 00000000654 10006037432 014724 0 ustar garg ecestaff
public interface Sensor extends MsgHandler { void localPredicateTrue(VectorClock vc); }dprogs/SensorCircToken.java.html 0000644 0002457 0000456 00000006143 10006037432 016525 0 ustar garg ecestaff
public class SensorCircToken extends CircToken implements MsgHandler, SensorUser { VCLinker comm; Sensor checker; int coordinator; int algoCode; public SensorCircToken(VCLinker comm, int coordinator, int algoCode) { super(comm, coordinator); this.comm = comm; this.coordinator = coordinator; this.algoCode = algoCode; } public void initiate() { if (algoCode==0) checker = new CentSensor(comm, this); else checker = new DistSensor(comm, this); if (!haveToken) checker.localPredicateTrue(comm.vc); super.initiate(); } public synchronized void sendToken() { super.sendToken(); if (!haveToken) checker.localPredicateTrue(comm.vc); } public synchronized void handleMsg(Message m, int src, String tag) { checker.handleMsg(m, src, tag); super.handleMsg(m, src, tag); } public void globalPredicateTrue(int v[]){ System.out.println("********************************************"); System.out.println("Global predicate tru. Cut:" + Util.writeArray(v)); } public void globalPredicateFalse(int pid){ System.out.println("********************************************"); System.out.println("Global predicate false. Process finished:" + pid); } }dprogs/SensorTester.java.html 0000644 0002457 0000456 00000002722 10006037432 016111 0 ustar garg ecestaff
public class SensorTester { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); VCLinker comm = new VCLinker(baseName, myId, numProc); int algoCode = Integer.parseInt(args[3]); SensorCircToken sp = new SensorCircToken( comm, Symbols.coordinator, algoCode); sp.initiate(); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, sp)).start(); } }dprogs/SensorUser.java.html 0000644 0002457 0000456 00000001103 10006037432 015551 0 ustar garg ecestaff
public interface SensorUser extends MsgHandler { void globalPredicateTrue(int v[]); void globalPredicateFalse(int pid); }dprogs/SeqMessage.java.html 0000644 0002457 0000456 00000001617 10006037432 015510 0 ustar garg ecestaff
public class SeqMessage { Message m; int seqNo; public SeqMessage(Message m, int seqNo) { this.m = m; this.seqNo = seqNo; } public int getSeqNo() { return seqNo; } public Message getMessage() { return m; } }dprogs/ShortestPath.java.html 0000644 0002457 0000456 00000004025 10006037432 016077 0 ustar garg ecestaff
public class ShortestPath extends Process { int parent = -1; int cost = -1; int edgeWeight[] = null; public ShortestPath(Linker initComm, int initCost[]) { super(initComm); edgeWeight = initCost; } public void initiate() { if (myId == Symbols.coordinator) { parent = myId; cost = 0; sendToNeighbors("path", cost); } } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("path")) { int dist = m.getMessageInt(); if ((parent == -1) || (dist + edgeWeight[source] < cost)) { parent = source; cost = dist + edgeWeight[source]; System.out.println("New cost is " + cost); sendToNeighbors("path", cost); } } } }dprogs/SimpleSynch.java.html 0000644 0002457 0000456 00000007335 10006037432 015714 0 ustar garg ecestaff
import java.util.LinkedList; public class SimpleSynch extends Process implements Synchronizer { int pulse = 0; MsgHandler prog; boolean rcvEnabled []; IntLinkedList pendingS = new IntLinkedList(); IntLinkedList pendingR = new IntLinkedList(); public SimpleSynch(Linker initComm) { super(initComm); rcvEnabled = new boolean[N]; for (int i = 0; i < N; i++) rcvEnabled[i] = false; } public synchronized void initialize(MsgHandler initProg) { prog = initProg; pendingS.addAll(comm.neighbors); notifyAll(); } public synchronized void handleMsg(Msg m, int src, String tag) { while (!rcvEnabled[src]) myWait(); pendingR.removeObject(src); if (pendingR.isEmpty()) notifyAll(); if (!tag.equals("synchNull")) prog.handleMsg(m, src, tag); rcvEnabled[src] = false; } public synchronized void sendMessage(int destId, String tag, int msg) { if (pendingS.contains(destId)) { pendingS.removeObject(destId); sendMsg(destId, tag, msg); } else System.err.println("Error: sending two messages/pulse"); } public synchronized void nextPulse() { while (!pendingS.isEmpty()) { // finish last pulse by sending null int dest = pendingS.removeHead(); sendMsg(dest, "synchNull", 0); } pulse ++; Util.println("**** new pulse ****:" + pulse); pendingS.addAll(comm.neighbors); pendingR.addAll(comm.neighbors); for (int i = 0; i < N; i++) rcvEnabled[i] = true; notifyAll(); while (!pendingR.isEmpty()) myWait(); } }dprogs/SpanTree.java.html 0000644 0002457 0000456 00000006613 10006037432 015175 0 ustar garg ecestaff
public class SpanTree extends Process { public int parent = -1; // no parent yet public IntLinkedList children = new IntLinkedList(); int numReports = 0; boolean done = false; public SpanTree(Linker initComm, boolean isRoot) { super(initComm); if (isRoot) { parent = myId; if (initComm.neighbors.size() == 0) done = true; else sendToNeighbors( "invite", myId); } } public void waitForDone() { // block till children known while (!done) myWait(); } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("invite")) { if (parent == -1) { numReports++; parent = source; sendMsg(source, "accept"); Util.println("Sending accept"); for (int i = 0; i < N; i++) if ((i != myId) && (i != source) && isNeighbor(i)) sendMsg(i, "invite"); } else sendMsg(source, "reject"); } else if ((tag.equals("accept")) || (tag.equals("reject"))) { if (tag.equals("accept")) children.add(source); numReports++; if (numReports == comm.neighbors.size()) { done = true; notify(); } } } }dprogs/StabTest.java.html 0000644 0002457 0000456 00000005140 10006037432 015177 0 ustar garg ecestaff
public class StabTest { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm = new Linker(baseName, myId, numProc); if (myId==0) { StableBottom bot = new StableBottom(comm); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, bot)).start(); bot.initiate(); while (true) { System.out.println(myId + " is not in CS"); bot.requestCS(); System.out.println(myId + " is in CS *****"); bot.releaseCS(); } } else { StableNormal normal = new StableNormal(comm); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, normal)).start(); while (true) { System.out.println(myId + " is not in CS"); normal.requestCS(); System.out.println(myId + " is in CS *****"); normal.releaseCS(); } } } }dprogs/StableBottom.java.html 0000644 0002457 0000456 00000006076 10006037432 016056 0 ustar garg ecestaff
import java.util.Timer; public class StableBottom extends Process implements Lock { int myState = 0; int leftState = 0; int next; Timer t = new Timer(); boolean tokenSent = false; public StableBottom(Linker initComm) { super(initComm); next = (myId + 1) % N; } public synchronized void initiate() { t.schedule(new RestartTask(this), 1000, 1000); } public synchronized void requestCS() { while (leftState != myState) myWait(); } public synchronized void releaseCS() { myState = (leftState + 1) % N; } public synchronized void sendToken() { if (!tokenSent) { sendMsg(next, "token", myState); tokenSent = true; } else tokenSent = false; } public synchronized void handleMsg(Message m, int src, String tag) { if (tag.equals("token") ) { leftState = m.getMessageInt(); notify(); Util.mySleep(1000); sendMsg(next, "token", myState); tokenSent = true; } else if (tag.equals("restart") ) sendToken(); } }dprogs/StableNormal.java.html 0000644 0002457 0000456 00000004037 10006037432 016035 0 ustar garg ecestaff
import java.util.Timer; public class StableNormal extends Process implements Lock { int myState = 0; int leftState = 0; public StableNormal(Linker initComm) { super(initComm); } public synchronized void requestCS() { while (leftState == myState) myWait(); } public synchronized void releaseCS() { myState = leftState; sendToken(); } public synchronized void sendToken() { int next = (myId + 1) % N; sendMsg(next, "token", myState); } public synchronized void handleMsg(Message m, int src, String tag) { if (tag.equals("token")) { leftState = m.getMessageInt(); notify(); Util.mySleep(1000); sendToken(); } } }dprogs/StableSpanNonroot.java.html 0000644 0002457 0000456 00000005750 10006037432 017070 0 ustar garg ecestaff
import java.util.Timer; public class StableSpanNonroot extends Process { int parent = -1; int dist = 0; int newDist = 0;//distance after recalculation Timer t = new Timer(); int numReports; public StableSpanNonroot(Linker initComm) { super(initComm); t.schedule(new RestartTask(this), 1000, 1000); } public synchronized void recalculate(){ newDist = N;//init newDist to max possible sendToNeighbors("Q.dist",0);//query neighbors for their dist numReports = comm.neighbors.size(); while (numReports > 0) myWait(); //wait for all responses dist = newDist; } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("Q.dist")) { sendMsg(source, "A.dist", dist); //reply with my dist } else if (tag.equals("A.dist")) { int hisDist = m.getMessageInt(); if ((hisDist>=0) && (newDist > hisDist)) { newDist = hisDist+1; parent = source; } numReports--; notifyAll(); } else if (tag.equals("restart")) { recalculate(); } } }dprogs/StableSpanRoot.java.html 0000644 0002457 0000456 00000003552 10006037432 016353 0 ustar garg ecestaff
import java.util.Timer; public class StableSpanRoot extends Process { int parent = -1; int dist = 0; Timer t = new Timer(); public StableSpanRoot(Linker initComm) { super(initComm); t.schedule(new RestartTask(this), 1000, 1000); } public synchronized void recalculate(){ parent = -1; dist = 0; } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("Q.dist")) { sendMsg(source, "A.dist", 0); } else if (tag.equals("restart")) { recalculate(); } } }dprogs/StableTreeTester.java.html 0000644 0002457 0000456 00000003547 10006037432 016700 0 ustar garg ecestaff
public class StableTreeTester { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm = new Linker(baseName, myId, numProc); if (myId==0) { StableSpanRoot bot = new StableSpanRoot(comm); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, bot)).start(); } else { StableSpanNonroot normal = new StableSpanNonroot(comm); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, normal)).start(); } } }dprogs/Symbols.java.html 0000644 0002457 0000456 00000003333 10006037432 015100 0 ustar garg ecestaff
public class Symbols { public static final int Infinity = -1; // internet related public static final String nameServer = "linux02.ece.utexas.edu"; public static final int ServerPort = 7039; public static final int coordinator = 0; // time bounds on messages in ms for synchronous algorithms public static final int roundTime = 500; public static final boolean debugFlag = true; }dprogs/SynchBfsTree.java.html 0000644 0002457 0000456 00000005514 10006037432 016012 0 ustar garg ecestaff
public class SynchBfsTree extends Process { int parent = -1; int level; Synchronizer s; boolean isRoot; public SynchBfsTree(Linker initComm, Synchronizer initS, boolean isRoot) { super(initComm); s = initS; this.isRoot = isRoot; } public void initiate() { if (isRoot) { parent = myId; level = 0; } s.initialize(this); for (int pulse = 0; pulse < N; pulse++) { if ((pulse == 0) && isRoot) { for (int i = 0; i < N; i++) if (isNeighbor(i)) s.sendMessage(i, "invite", level + 1); } s.nextPulse(); } } public void handleMsg(Msg m, int src, String tag) { if (tag.equals("invite")) { if (parent == -1) { parent = src; level = m.getMessageInt(); Util.println(myId + " is at level " + level); for (int i = 0; i < N; i++) if (isNeighbor(i) && (i != src)) s.sendMessage(i, "invite", level + 1); } } } }dprogs/SynchLinker.java.html 0000644 0002457 0000456 00000012172 10006037432 015702 0 ustar garg ecestaff
import java.io.*; public class SynchLinker extends Linker { final static int passive = 0, active = 1; int state = active; private boolean granted; public SynchLinker(String basename, int id, int numProc) throws Exception { super(basename, id, numProc); } public synchronized void sendMsg(int destId, String tag,String msg) { if (destId < myId) { // big message waitForActive(); super.sendMsg(destId, "app", " "); super.sendMsg(destId, tag, msg); state = passive; } else { // small message granted = false; super.sendMsg(destId, "request", " "); while (!granted) Util.myWait(this);// wait for permission super.sendMsg(destId, "app", " "); super.sendMsg(destId, tag, msg); } } synchronized void turnActive(){ state = active; notifyAll(); } synchronized void waitForActive(){ while (state != active) Util.myWait(this); } synchronized void grant(){ granted = true; notifyAll(); } public Msg receiveMsg(int fromId) throws IOException { boolean done = false; Msg m = null; while (!done) { // app msg received m = super.receiveMsg(fromId); String tag = m.getTag(); if (tag.equals("app")) { if (m.getSrcId() > myId) { // big message waitForActive(); m = super.receiveMsg(fromId); super.sendMsg(fromId, "ack", " "); } else { // small message m = super.receiveMsg(fromId); turnActive(); } done = true; } else if (tag.equals("ack")) turnActive(); else if (tag.equals("request")) { waitForActive(); super.sendMsg(fromId, "permission", " "); } else if (tag.equals("permission")) grant(); } return m; } }dprogs/Synchronizer.java.html 0000644 0002457 0000456 00000001513 10006037432 016143 0 ustar garg ecestaff
public interface Synchronizer { public void initialize();// initialize the synchronizer public void sendMessage(int destId, String tag, int msg); public void nextPulse();// block for the next pulse }dprogs/TermDetector.java.html 0000644 0002457 0000456 00000001416 10006037432 016051 0 ustar garg ecestaff
public interface TermDetector { public void initiate(); public void sendAction(); public void turnPassive(); public void handleMsg(Message m, int srcsId, String tag); }dprogs/TermShortestPath.java.html 0000644 0002457 0000456 00000003125 10006037432 016727 0 ustar garg ecestaff
public class TermShortestPath extends ShortestPath { TermDetector td = null; public TermShortestPath(Linker initComm, int initCost[], TermDetector td) { super(initComm, initCost); this.td = td; } public void initiate() { super.initiate(); td.initiate(); } public void sendMsg(int dest, String tag, int msg) { super.sendMsg(dest, tag, msg); td.sendAction(); } public synchronized void handleMsg(Message m, int source, String tag) { td.handleMsg(m, source, tag); super.handleMsg(m, source, tag); td.turnPassive(); } }dprogs/TermTester.java.html 0000644 0002457 0000456 00000006127 10006037432 015552 0 ustar garg ecestaff
import java.util.Random; public class TermTester { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm = new Linker(baseName, myId, numProc); int[] edgeCost = new int[numProc]; Random r = new Random(); for (int i = 0; i < numProc; i++) if (i != myId) edgeCost[i] = r.nextInt(1000); edgeCost[myId] = 0; for (int i = 0; i < numProc; i++) System.out.println("weight of(" + i + "," + myId + ")=" + edgeCost[i]); int alg = Integer.parseInt(args[3]); ShortestPath sp = null; if (alg == 0) sp = new ShortestPath(comm, edgeCost); else if (alg == 1) sp = new TermShortestPath(comm, edgeCost, new DSTerm(comm)); else if (alg == 2) sp = new TermShortestPath(comm, edgeCost, new TermToken(comm)); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, sp)).start(); sp.initiate(); // start the computation } }dprogs/TermToken.java.html 0000644 0002457 0000456 00000010442 10006037432 015357 0 ustar garg ecestaff
import java.util.*; public class TermToken extends Process implements TermDetector { final static int passive = 0, active = 1, white = 0, black = 1; int state = passive, color = white; int c = 0; int next; boolean haveToken = false; int tokenCount = 0, tokenColor = white; public TermToken(Linker initComm) { super(initComm); next = (myId + 1) % N; } public void initiate() { if (myId==Symbols.coordinator) { if (state == passive) sendToken(); else haveToken = true; } } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("termToken")) { haveToken = true; StringTokenizer st = new StringTokenizer(m.getMessage()); tokenColor = Integer.parseInt(st.nextToken()); tokenCount = Integer.parseInt(st.nextToken()); if (myId==Symbols.coordinator) { if ((c + tokenCount == 0) && (color == white) && (state == passive) && (tokenColor == white)) { System.out.println("Termination Detected"); haveToken = false; } } if ((state == passive) && haveToken) sendToken(); } else { // application message state = active; color = black; c = c - 1; } } public void sendAction() { c = c + 1; } public void turnPassive() { state = passive; if (haveToken) sendToken(); } synchronized void sendToken() { if (myId==Symbols.coordinator) sendMsg(next, "termToken", white, 0); else if ((color == black) || (tokenColor == black)) sendMsg(next, "termToken", black, c + tokenCount); else sendMsg(next, "termToken", white, c + tokenCount); haveToken = false; color = white; } }dprogs/Topology.java.html 0000644 0002457 0000456 00000003532 10006037432 015265 0 ustar garg ecestaff
import java.io.*; import java.util.*; public class Topology { public static void readNeighbors(int myId, int N, IntLinkedList neighbors) { Util.println("Reading topology"); try { BufferedReader dIn = new BufferedReader( new FileReader("topology" + myId)); StringTokenizer st = new StringTokenizer(dIn.readLine()); while (st.hasMoreTokens()) { int neighbor = Integer.parseInt(st.nextToken()); neighbors.add(neighbor); } } catch (FileNotFoundException e) { for (int j = 0; j < N; j++) if (j != myId) neighbors.add(j); } catch (IOException e) { System.err.println(e); } Util.println(neighbors.toString()); } }dprogs/TotalChat.java.html 0000644 0002457 0000456 00000003767 10006037432 015346 0 ustar garg ecestaff
import java.io.*; import java.util.*; public class TotalChat { public static void main(String[] args) throws Exception { int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm = new Linker(args[0], myId, numProc); Chat chat = new Chat(comm); TotalOrder t = new TotalOrder(comm, chat); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, t)).start(); BufferedReader din = new BufferedReader(new InputStreamReader(System.in)); while (true) { String chatMsg = chat.getUserInput(din); if (chatMsg.equals("quit")) break; IntLinkedList destIds = chat.getDest(din); t.multicast(destIds, "chat", chatMsg); } } }dprogs/Tree.java.html 0000644 0002457 0000456 00000004145 10006037432 014351 0 ustar garg ecestaff
public class Tree extends Process { int parent = -1; int level; public Tree(Linker initComm, boolean isRoot) { super(initComm); if (isRoot) initiate(); } public void initiate() { parent = myId; level = 0; for (int i = 0; i < N; i++) if (isNeighbor(i)) sendMsg(i, "invite", level); myWait(); } public synchronized void handleMsg(Message m, int source, String tag) { if (tag.equals("invite")) { if (parent == -1) { parent = source; level = m.getMessageInt(); for (int i = 0; i < N; i++) if (isNeighbor(i) && (i != source)) sendMsg(i, "invite", level + 1); } } } }dprogs/TwoPhaseCoord.java.html 0000644 0002457 0000456 00000005176 10006037432 016200 0 ustar garg ecestaff
public class TwoPhaseCoord extends Process { boolean globalCommit = false; boolean donePhase1 = false; boolean noReceived = false; int numParticipants; int numReplies = 0; public TwoPhaseCoord(Linker initComm) { super(initComm); numParticipants = N - 1; } public synchronized void doCoordinator() { // Phase 1 broadcastMsg("request", myId); while (!donePhase1) myWait(); // Phase 2 if (noReceived) broadcastMsg("finalAbort", myId); else { globalCommit = true; broadcastMsg("finalCommit", myId); } } public synchronized void handleMsg(Msg m, int src, String tag) { if (tag.equals("yes")) { numReplies++; if (numReplies == numParticipants) { donePhase1 = true; notify(); } } else if (tag.equals("no")) { noReceived = true; donePhase1 = true; notify(); } } }dprogs/TwoPhaseParticipant.java.html 0000644 0002457 0000456 00000005312 10006037432 017400 0 ustar garg ecestaff
public class TwoPhaseParticipant extends Process { boolean localCommit; boolean globalCommit; boolean done = false; boolean hasProposed = false; public TwoPhaseParticipant(Linker initComm) { super(initComm); } public synchronized void propose(boolean vote) { localCommit = vote; hasProposed = true; notify(); } public synchronized boolean decide() { while (!done) myWait(); return globalCommit; } public synchronized void handleMsg(Msg m, int src, String tag) { while (!hasProposed) myWait(); if (tag.equals("request")) { if (localCommit) sendMsg(src, "yes"); else sendMsg(src, "no"); } else if (tag.equals("finalCommit")) { globalCommit = true; done = true; notify(); } else if (tag.equals("finalAbort")) { globalCommit = false; done = true; notify(); } } }dprogs/TwoPhaseTester.java.html 0000644 0002457 0000456 00000004511 10006037432 016370 0 ustar garg ecestaff
public class TwoPhaseTester { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm = new Linker(baseName, myId, numProc); if (myId == 0) { TwoPhaseCoord master = new TwoPhaseCoord(comm); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, master)).start(); master.doCoordinator(); } else { TwoPhaseParticipant slave = new TwoPhaseParticipant(comm); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, slave)).start(); if (args[3].equals("t")) slave.propose(true); else slave.propose(false); System.out.println("The value decided:" + slave.decide()); } } }dprogs/Util.java.html 0000644 0002457 0000456 00000011424 10006037432 014365 0 ustar garg ecestaff
import java.util.*; public class Util { public static int max(int a, int b) { if (a > b) return a; return b; } public static void mySleep(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { } } public static void myWait(Object obj) { try { obj.wait(); } catch (InterruptedException e) { } } public static boolean lessThan(int A[], int B[]) { for (int j = 0; j < A.length; j++) if (A[j] > B[j]) return false; for (int j = 0; j < A.length; j++) if (A[j] < B[j]) return true; return false; } public static int maxArray(int A[]) { int v = A[0]; for (int i=0; i<A.length; i++) if (A[i] > v) v = A[i]; return v; } public static String writeArray(int A[]){ StringBuffer s = new StringBuffer(); for (int j = 0; j < A.length; j++) s.append(String.valueOf(A[j]) + " "); return new String(s.toString()); } public static void readArray(String s, int A[]) { StringTokenizer st = new StringTokenizer(s); for (int j = 0; j < A.length; j++) A[j] = Integer.parseInt(st.nextToken()); } public static int searchArray(int A[], int x) { for (int i = 0; i < A.length; i++) if (A[i] == x) return i; return -1; } public static void println(String s){ if (Symbols.debugFlag) { System.out.println(s); System.out.flush(); } } }dprogs/VCLinker.java.html 0000644 0002457 0000456 00000004613 10006037432 015127 0 ustar garg ecestaff
public class VCLinker extends Linker { public VectorClock vc; int receiveTag[] = null; public VCLinker(String basename, int id, int N) throws Exception { super(basename, id, N); vc = new VectorClock(N, id); receiveTag = new int[N]; } public void sendMsg(int destId, String tag, String msg) { super.sendMsg(destId, "vector", vc.toString()); super.sendMsg(destId, tag, msg); vc.sendAction(); } public void simpleSendMsg(int destId, String tag, String msg) { super.sendMsg(destId, tag, msg); } public Msg receiveMsg(int fromId) throws java.io.IOException { Msg m1 = super.receiveMsg(fromId); if (m1.getTag().equals("vector")) { Util.readArray(m1.getMessage(), receiveTag); vc.receiveAction(receiveTag); Msg m = super.receiveMsg(fromId);//app message return m; } else return m1; } }dprogs/VectorClock.java.html 0000644 0002457 0000456 00000004046 10006037432 015670 0 ustar garg ecestaff
public class VectorClock { public int[] v; int myId; int N; public VectorClock(int numProc, int id) { myId = id; N = numProc; v = new int[numProc]; for (int i = 0; i < N; i++) v[i] = 0; v[myId] = 1; } public void tick() { v[myId]++; } public void sendAction() { //include the vector in the message v[myId]++; } public void receiveAction(int[] sentValue) { for (int i = 0; i < N; i++) v[i] = Util.max(v[i], sentValue[i]); v[myId]++; } public int getValue(int i) { return v[i]; } public String toString(){ return Util.writeArray(v); } }dprogs/AlphaSynch.java 0000644 0002457 0000456 00000003644 10006037440 014543 0 ustar garg ecestaff import java.util.LinkedList; public class AlphaSynch extends Process implements Synchronizer { int pulse = -1; int acksNeeded = 0; IntLinkedList unsafe = new IntLinkedList(); LinkedList nextPulseMsgs = new LinkedList();//msgs for next pulse boolean meSafe; MsgHandler prog; public AlphaSynch(Linker initComm) { super(initComm); } public synchronized void initialize(MsgHandler initProg) { prog = initProg; startPulse(); notifyAll(); } void startPulse(){ unsafe.addAll(comm.neighbors); meSafe = false; pulse ++; Util.println("**** new pulse ****:" + pulse); } public synchronized void handleMsg(Msg m, int src, String tag) { while (pulse < 0) myWait(); if (tag.equals("synchAck")) { acksNeeded--; if (acksNeeded == 0) notifyAll(); } else if (tag.equals("safe")) { while (!unsafe.contains(src)) myWait(); unsafe.removeObject(src); if (unsafe.isEmpty()) notifyAll(); } else { // application message sendMsg(src, "synchAck", 0); while (!unsafe.contains(src)) myWait(); if (meSafe) nextPulseMsgs.add(m); else prog.handleMsg(m, src, tag); } } public synchronized void sendMessage(int destId, String tag, int msg) { acksNeeded++; sendMsg(destId, tag, msg); } public synchronized void nextPulse() { while (acksNeeded != 0) myWait(); meSafe = true; sendToNeighbors("safe", 0); while (!unsafe.isEmpty()) myWait(); startPulse(); while (!nextPulseMsgs.isEmpty()) {//act on msgs received earlier Msg m = (Msg) nextPulseMsgs.removeFirst(); prog.handleMsg(m, m.getSrcId(), m.getTag()); } notifyAll(); } } dprogs/BGATester.java 0000644 0002457 0000456 00000001034 10006037440 014260 0 ustar garg ecestaff public class BGATester { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Linker comm = new Linker(baseName, myId, numProc); KingBGA sp = new KingBGA(comm, 2); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, sp)).start(); sp.propose(myId % 2); System.out.println("The value decided:" + sp.decide()); } } dprogs/BetaSynch.java 0000644 0002457 0000456 00000004057 10006037440 014370 0 ustar garg ecestaff import java.util.*; public class BetaSynch extends Process implements Synchronizer { int pulse, acksNeeded; IntLinkedList unsafeKids = new IntLinkedList(); MsgHandler prog; SpanTree tree; private boolean pulseMsg; public BetaSynch(Linker initComm, boolean isRoot) { super(initComm); tree = new SpanTree(comm, isRoot); pulse = 0; } public void initialize(MsgHandler initProg) { prog = initProg; pulse = 0; acksNeeded = 0; pulseMsg = false; unsafeKids.addAll(tree.children); } public synchronized void handleMsg(Msg m, int src, String tag) { if (tag.equals("synchAck")) { acksNeeded--; if (acksNeeded == 0) notify(); } else if (tag.equals("subtreeSafe")) { unsafeKids.remove(src); if (unsafeKids.isEmpty()) { if (tree.parent == -1) sendChildrenPulse(); else sendMsg(tree.parent, "subTreeSafe", pulse); } } else if (tag.equals("pulse")) { sendChildrenPulse(); } else { // application msg. handle only if pulse number matches //else put back in queue prog.handleMsg(m, src, tag); sendMsg(src, "synchAck", 0); } } private void sendChildrenPulse() { pulseMsg = true; ListIterator t = tree.children.listIterator(0); while (t.hasNext()) { Integer child = (Integer) t.next(); sendMsg(child.intValue(), "pulse", pulse); } notify(); } public void sendMessage(int destId, String tag, int msg) { acksNeeded++; sendMsg(destId, tag, msg); } public void nextPulse() { while (acksNeeded != 0) myWait(); while (tree.children.isEmpty()) sendMsg(tree.parent, "subtreeSafe", pulse); while (!pulseMsg) myWait(); pulse++; //the node moves to next pulse // initialize(); } } dprogs/CamCircToken.java 0000644 0002457 0000456 00000000442 10006037440 015004 0 ustar garg ecestaff public class CamCircToken extends CircToken implements CamUser { public CamCircToken(Linker initComm, int coordinator) { super(initComm, coordinator); } public synchronized void localState() { Util.println("local state: haveToken=" + haveToken); } } dprogs/CamUser.java 0000644 0002457 0000456 00000000112 10006037440 014033 0 ustar garg ecestaff public interface CamUser extends MsgHandler { void localState(); } dprogs/Camera.java 0000644 0002457 0000456 00000000112 10006037440 013664 0 ustar garg ecestaff public interface Camera extends MsgHandler { void globalState(); } dprogs/CameraLinker.java 0000644 0002457 0000456 00000002352 10006037440 015041 0 ustar garg ecestaff import java.util.*; import java.net.*; import java.io.*; public class CameraLinker extends Linker { static final int white = 0, red = 1; int seqNo[] = null; SenderCamera cam; public CameraLinker(String basename, int myId, int numProc) throws Exception { super(basename, myId, numProc); seqNo = new int[numProc]; for (int i = 0; i < numProc; i++) seqNo[i] = 0; } public void initCam(SenderCamera cam){ this.cam = cam; } public void sendMsg(int destId, String tag, String msg) { if ((tag.equals("marker")) || (tag.equals("ack"))) super.sendMsg(destId, tag, msg); else {// send seq numbers with app msgs seqNo[destId]++; Msg m = new Msg(myId, destId, tag, msg); if (cam.myColor == white) { cam.recordMsg(destId, new SeqMessage(m, seqNo[destId])); super.sendMsg(destId, "white", String.valueOf(seqNo[destId]) +" "+ m.toString()+" "); } else super.sendMsg(destId, "red", String.valueOf(seqNo[destId]) +" "+ m.toString()+" "); } } } dprogs/CameraTester.java 0000644 0002457 0000456 00000001640 10006037440 015062 0 ustar garg ecestaff import java.util.Random; public class CameraTester { public static void main(String[] args) throws Exception { String baseName = args[0]; int myId = Integer.parseInt(args[1]); int numProc = Integer.parseInt(args[2]); Camera camera = null; CamCircToken sp = null; if (args[3].equals("RecvCamera")) { Linker comm = new Linker(baseName, myId, numProc); sp = new CamCircToken(comm, 0); camera = new RecvCamera(comm, sp); } if (args[3].equals("SenderCamera")) { CameraLinker comm = new CameraLinker(args[0], myId, numProc); sp = new CamCircToken(comm, 0); camera = new SenderCamera(comm, sp); } sp.initiate(); for (int i = 0; i < numProc; i++) if (i != myId) (new ListenerThread(i, camera)).start(); if (myId == 0) camera.globalState(); } } dprogs/CausalLinker.java 0000644 0002457 0000456 00000004542 10006037440 015064 0 ustar garg ecestaff import java.util.*; import java.net.*; import java.io.*; public class CausalLinker extends Linker { int M[][]; LinkedList deliveryQ = new LinkedList(); // deliverable messages LinkedList pendingQ = new LinkedList(); // messages with matrix public CausalLinker(String basename, int id, int numProc) throws Exception { super(basename, id, numProc); M = new int[N][N]; Matrix.setZero(M); } public synchronized void sendMsg(int destId, String tag, String msg){ M[myId][destId]++; super.sendMsg(destId, "matrix", Matrix.write(M)); super.sendMsg(destId, tag, msg); } public synchronized void multicast(IntLinkedList destIds, String tag, String msg) { for (int i=0; i