-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLamportClient.java
More file actions
96 lines (76 loc) · 3.27 KB
/
Copy pathLamportClient.java
File metadata and controls
96 lines (76 loc) · 3.27 KB
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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logicalclock;
import java.util.ArrayList;
import java.util.Random;
/**
*
* @author Ian Gortan
*/
public class LamportClient implements Runnable {
private MessageBuffer buffer;
final private int NUM_EVENTS = 10;
private int pid;
public LamportClient(MessageBuffer buf, int pid) {
this.buffer = buf;
this.pid = pid;
}
public void run() {
Random random = new Random();
//start at -1 just so we can index in to events array easily
int clock = -1;
ArrayList<String> events = new ArrayList<String> ();
// create a message object
Message m = new Message (pid, clock, "init");
m.setPid(pid);
m.setClock(clock) ;
// add some 'reandomness' to the order at startup
if ( (pid%2) == 0 ) {
clock++;
m.setClock(clock);
String event = "[INTERNAL] " + "PID=" + Integer.toString(pid) + " CLOCK:" + Integer.toString(clock);
events.add(event);
}
for (int i = 0; i < NUM_EVENTS ; i++ ) {
// let's generate an event
clock++;
m.setClock(clock);
if ( ((i%2) == 0) ) {
// internal event
String event = "[INTERNAL] " + "PID=" + Integer.toString(pid) + " CLOCK:" + Integer.toString(clock);
events.add(event);
} else {
// external event
String event = "[SEND] " + "PID=" + Integer.toString(pid) + " CLOCK:" + Integer.toString(clock);
events.add(event);
m.setMessageID(event);
buffer.put(m); // sleep for a random time to induce different orders
try {
Thread.sleep(random.nextInt(2000));
} catch (InterruptedException e) {}
// get a message and set clock according to Lamport algorithm
//System.out.println("Getting a message: " + Integer.toString(pid));
Message recMsg = buffer.get(pid);
// chck it wasn't a message we sent (null returned) as we want to ignore those
if (recMsg != null) {
// add the event ...
if (recMsg.getClock() > clock) {
clock = recMsg.getClock() + 1;
} else {
clock++;
}
event = "[RECEIVE] " + "FROM PID=" + Integer.toString(recMsg.getPid()) + " CLOCK IN:" + Integer.toString(recMsg.getClock()) + " LOCAL CLOCK " + Integer.toString(clock);
events.add(event);
}
}
}
System.out.println("Process " + pid + " complete and ending");
// your code
for (String event: events) {
System.out.println(event);
}
}
}