33import java .util .HashSet ;
44import java .util .Random ;
55
6+ class Channel {
7+ public volatile String message = "" ;
8+ public void putMessage (String s ){
9+ message = s ;
10+ }
11+ public String getMessage (){
12+ return message ;
13+ }
14+ }
15+
616class Process implements Runnable {
717
18+ public static ArrayList <Channel > fromMaster = new ArrayList <Channel >();
19+ public static ArrayList <Channel > toMaster = new ArrayList <Channel >();
820 @ Override
921 public void run () {
1022 // TODO Auto-generated method stub
1123 if (type .equals ("master" )) {// master starts the rounds
1224 ids = new int [n ];
13- messagesFromMaster = new String [n ];
14- messagesToMaster = new String [n ];
1525 spawnThreads ();
1626 while (!leaderElected ) {
1727 // initiate rounds
1828
1929 for (int i = 0 ; i < n ; i ++) {
20- messagesFromMaster [ i ] = "START" ;
30+ fromMaster . get ( i ). putMessage ( "START" ) ;
2131 System .out .println ("master> Sending message to slave " + i );
22- messagesToMaster [i ] = "" ;
2332 }
24- while (!roundDone ) {
25- roundDone = isRoundDone ();
33+ while (!isRoundDone () ) {
34+
2635 //System.out.println("master> Waiting for DONE messages from slaves!" );
2736 }
2837 leaderElected = true ;
@@ -31,8 +40,8 @@ public void run() {
3140 System .exit (0 );
3241 } else {// Participant in HS Algorithm
3342 while (true ) {
34- if (messagesFromMaster [ index ] .equals ("START" )) {
35- messagesFromMaster [ index ] = "" ;
43+ if (fromMaster . get ( index ). getMessage () .equals ("START" )) {
44+ fromMaster . get ( index ). putMessage ( "" ) ;
3645 // round
3746 round ();
3847 }
@@ -49,25 +58,24 @@ public void run() {
4958 public int currentPhase = 0 ;
5059
5160 public void round () {
52- messagesToMaster [ index ] = "DONE" ;
61+ toMaster . get ( index ). putMessage ( "DONE" ) ;
5362 System .out .println ("slave " + index + "> Sending DONE message back to master" );
5463 }
5564
5665 public boolean isRoundDone () {
57- boolean bDone = true ;
58- if (!roundDone ){
66+
5967 for (int i = 0 ; i < n ; i ++) {
60- if (messagesToMaster [i ].equals ("DONE" )) {
61- //bDone = bDone && true;
62- return roundDone ;
63- //System.out.println("master> Received DONE from " + i);
68+ if (!toMaster .get (i ).getMessage ().equals ("DONE" )) {
69+ return false ;
6470 }
6571
6672 }
67- }
68- roundDone = true ;
69- return roundDone ;
73+ return true ;
74+
7075 }
76+
77+
78+
7179
7280 public Process (int id , int index ) {
7381 this .id = id ;
@@ -84,9 +92,11 @@ public void spawnThreads() {
8492 while (set .contains (ids [i ])) {
8593 ids [i ] = random .nextInt (Integer .MAX_VALUE );
8694 }
95+ Channel inbound = new Channel ();
96+ Channel outbound = new Channel ();
97+ toMaster .add (inbound );
98+ fromMaster .add (outbound );
8799 set .add (ids [i ]);
88- messagesFromMaster [i ] = "" ;
89- messagesToMaster [i ] = "" ;
90100 Process p = new Process (ids [i ], i );
91101 p .type = "slave" ;
92102 list .add (p );
0 commit comments