-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCurrencyThread.java
290 lines (250 loc) · 9.33 KB
/
CurrencyThread.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import java.net.*;
import java.io.*;
import java.util.*;
@SuppressWarnings("unused")
public class CurrencyThread extends Thread
{
static Random generator = new Random();
CurrencyValue c = new CurrencyValue();
private Socket socket1 = null;
private Socket socket2 = null;
private String type;
private static int processId;
private String buffer;
private int cTicks;
private static double counter;
private static Message msg_temp;
private static int iterations;
private static BufferedWriter writer;
private static ArrayList<Message> queue = new ArrayList<Message>();
private static ArrayList<String> ack_queue = new ArrayList<String>();
private static ArrayList<Message> tQueue = new ArrayList<Message>();
static int count_update;
static int count_remove; // Counts the number of processed transactions(Final count of transactions)
static int addCount;
static int finishCount=0;
private static int flag_ready_for_Remove = 0;
private static int flag_acknowledgement_Receieved=0;
private static int flag_update_found_in_Queue=0;
// Constructor for dispatcher and worker threads
public CurrencyThread(Socket socket1,Socket socket2,String type,int pId, int i)
{
super("CurrencyThread");
this.socket1 = socket1;
this.socket2 = socket2;
this.type=type;
processId=pId;
iterations=i;
}
// synchronizer for finish count
public static synchronized void counter(String type)
{
if(type.equals("finishCount"))
{
finishCount++;
if(finishCount==2)
{
System.out.println("All Processes are done with the transactions. Process P"+processId+" terminated gracefully");
logging("All finished. p"+processId+" is terminating",2);
}
}
}
// Queue operations
public static synchronized void queue_modify(Message message,String op)
{
if(op.equals("ADD"))
{
// debugging code for the problem of acknowledgment received for a message before receiving an update message problem
if(ack_queue.indexOf(message.mSerial)!=-1)
{
flag_acknowledgement_Receieved=1;
ack_queue.remove(ack_queue.indexOf(message.mSerial));
}
queue.add(message);
Collections.sort(queue, new SortQueue());
}
else if(op.equals("UPDATE"))
{
flag_update_found_in_Queue = 0;
flag_ready_for_Remove=0;
for (Message temp : queue)
{
if(temp.mSerial.equals(message.mSerial))
{
flag_update_found_in_Queue=1;
temp.ack++;
if(temp.ack==2) //If ack count is 2, process the transaction
{
CurrencyValue.update_currency(temp.dx,temp.dy);
flag_ready_for_Remove=1;
msg_temp=temp;
}
}
}
//debugging code for "acknowledgment received for a message before receiving an update message" problem
if(flag_update_found_in_Queue==0)ack_queue.add(message.mSerial);
}
else
{
queue.remove(msg_temp);
count_remove++;
System.out.println("After Tansaction "+count_remove+": X:"+CurrencyValue.x+" Y:"+CurrencyValue.y);
logging("[ OP"+count_remove+" : C"+(double)msg_temp.clock+" ] "+"CurrencyValue value is set to ("+CurrencyValue.x+","+CurrencyValue.y+") by ("+msg_temp.dx+","+msg_temp.dy+")",2);
flag_ready_for_Remove=0;
}
}
public void run()
{
if(type.equals("D")) //dispatched thread
{
try
{
PrintWriter out_1 = new PrintWriter(socket1.getOutputStream(), true);
PrintWriter out_2 = new PrintWriter(socket2.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
while((buffer = in.readLine())!=null)
{
String tokens[] = buffer.split(":");
Message message = new Message();
// Check if the received message is Update
if (tokens[0].equals("U"))
{
// Build the update Message to push into the queue
double tempCounter=++counter;
message.mtype = tokens[0];
message.pid = Integer.parseInt(tokens[1]);
message.mSerial = tokens[2];
message.dx = Integer.parseInt(tokens[3]);
message.dy = Integer.parseInt(tokens[4]);
message.clock = Double.parseDouble(tokens[5]);
message.ack = Integer.parseInt(tokens[6]);
// Adjust local clock counter
if(tempCounter<message.clock)
{
tempCounter = (int)Math.max(tempCounter, message.clock);
counter = tempCounter+processId*0.1+1;
}
flag_acknowledgement_Receieved=0;
queue_modify(message,"ADD"); //
if(flag_acknowledgement_Receieved==1)
{
queue_modify(message,"UPDATE");
if(flag_ready_for_Remove==1)
queue_modify(message,"REMOVE");
}
// Building an Acknowledge message and broadcast to other servers
counter++;
String temp = "A"+":"+processId+":"+message.mSerial+":"+counter;
out_1.println(temp);
out_2.println(temp);
}
else if(tokens[0].equals("A")) // for ack messages
{
double tempCounter=++counter;
message.mtype = tokens[0];
message.pid = Integer.parseInt(tokens[1]);
message.mSerial = tokens[2];
message.clock = Double.parseDouble(tokens[3]);
if(tempCounter<message.clock)
{
tempCounter = (int)Math.max(tempCounter, message.clock); // counter adjustment
counter = tempCounter+processId*0.1+1;
}
// Check the queue for the corresponding message and increment the ack variable by 1
flag_ready_for_Remove=0;
queue_modify(message,"UPDATE");
if(flag_ready_for_Remove==1)queue_modify(msg_temp,"REMOVE"); // After processing remove the message from the queue
if(count_remove==iterations*3)
{
String finish = "F"+":"+processId;
out_1.println(finish);
out_2.println(finish);
}
}
else // Code for processing Finish message
{
message.mtype = tokens[0];
message.pid = Integer.parseInt(tokens[1]);
System.out.println("Process p"+message.pid+" is done with all transactions ");
logging("p"+message.pid+" finished.",2);
counter("finishCount");
}
}
out_1.close();
out_2.close();
in.close();
// socket1.close();
// socket2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Worker Thread begins here
else if (type.equals("W"))
{
try
{
for(int i = 0; i < iterations ; i++)
{
int interval = rand(1,1000,generator);
try
{
Thread.sleep(interval);
}
catch(InterruptedException e)
{
System.out.println("exception");
}
double tempCounter=++counter;
String mssg_type = "U";
int delx = rand(-80,80,generator);
int dely = rand(-80,80,generator);
Message message = new Message(mssg_type, "M"+processId+i ,processId, delx, dely, tempCounter, 0);
queue_modify(message,"ADD"); //Add the message to the local queue
String ack = message.mtype+":"+message.pid+":"+message.mSerial+":"+message.dx+":"+message.dy+":"+message.clock+":"+"1";
PrintWriter out_1 = new PrintWriter(socket1.getOutputStream(), true);
PrintWriter out_2= new PrintWriter(socket2.getOutputStream(), true);
out_1.println(ack);
out_2.println(ack);
}
}catch (IOException e)
{
e.printStackTrace();
}
}
}
// Random number generator
public static int rand(int start, int end, Random r)
{
long range = (long)end - (long)start + 1;
long fraction = (long)(range * r.nextDouble());
int randomNumber = (int)(fraction + start);
return(randomNumber);
}
// method for logging
public static synchronized void logging(String s1,int x){
FileWriter fstream;
Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String timeStamp = "[ " + String.format("%02d",(cal.get(Calendar.MONTH) + 1)) +
"/" + String.format("%02d",cal.get(Calendar.DAY_OF_MONTH)) +
" "+String.format("%02d",cal.get(Calendar.HOUR_OF_DAY))+
":"+String.format("%02d",cal.get(Calendar.MINUTE))+
":"+String.format("%02d",cal.get(Calendar.SECOND))+
" ]";
try
{
fstream = new FileWriter("log"+processId+".txt", true);
writer = new BufferedWriter(fstream);
if(x==2)
writer.write(timeStamp+" "+s1+"\n");
else
writer.write(s1);
writer.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}