0% found this document useful (0 votes)
238 views10 pages

Lamport's Clock Algorithm in Java

The document details the implementation of Lamport's Clock Algorithm in Java, focusing on the concept of logical clocks in distributed systems. It explains the algorithm's mechanism for establishing a partial ordering of events based on timestamps assigned by local logical clocks. The lab reinforces the importance of logical time for coordinating processes without relying on synchronized physical clocks.

Uploaded by

Rhea Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
238 views10 pages

Lamport's Clock Algorithm in Java

The document details the implementation of Lamport's Clock Algorithm in Java, focusing on the concept of logical clocks in distributed systems. It explains the algorithm's mechanism for establishing a partial ordering of events based on timestamps assigned by local logical clocks. The lab reinforces the importance of logical time for coordinating processes without relying on synchronized physical clocks.

Uploaded by

Rhea Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Implementation of Lamport’s Clock

Algorithm Using JAVA


1. Objectives
• To understand the concept of logical clocks in distributed systems and how they differ
from physical clocks.

• To learn the Lamport’s Logical Clock Algorithm to establish a partial ordering of


events in a distributed environment.

2. Theory
Introduction
Each process within a distributed system maintains its own local counter, which is referred to
as a logical clock. These logical clocks do not measure real-world physical time; instead, they
provide a sequential ordering for events, reflecting their causal relationships. The numerical
value assigned by a logical clock to an event is known as its timestamp.
Lamport’s Clock Algorithm, introduced by Leslie Lamport in 1978, is a logical clock
mechanism used in distributed systems to order events without relying on synchronized
physical clocks. In a distributed system, events occur across multiple processes, and es-
tablishing a consistent order is crucial for understanding causality. The algorithm assigns
timestamps to events based on logical clocks maintained by each process, ensuring that if
one event causally precedes another, its timestamp is less than that of the subsequent event.
The pivotal property that Lamport’s logical clocks are designed to satisfy is the Clock
Condition: If event ’a’ happened before event ’b’ (a → b), then the logical timestamp of
’a’ (C(a)) must be strictly less than the logical timestamp of ’b’ (C(b)). This condition
establishes a unidirectional causal guarantee. It ensures that if a causal relationship exists
between two events, their respective timestamps will accurately reflect that order. However,
the converse of the Clock Condition is not guaranteed. That is, if C(a) < C(b), it does not
necessarily imply that a → b.

3. Algorithm
1. Initialization: Each process Pi maintains a logical clock Ci , initialized to 0.

1
2. Internal Event at Pi :

• Increment Ci : Ci = Ci + 1.
• Assign Ci as the timestamp for the event.

3. Send Event from Pi to Pj :

• Increment Ci : Ci = Ci + 1.
• Assign Ci as the timestamp for the event.
• Include Ci in the message to Pj .

4. Receive Event at Pi with message timestamp T :

• Update Ci : Ci = max(Ci , T ) + 1.
• Assign Ci as the timestamp for the event.

5. Ordering: Events are ordered globally by their timestamps. Ties are resolved using
process IDs if needed.

4. Source Code
[Link]

1 import [Link].*;
2

3 class Process {
4 private int processId;
5 private int logicalClock;
6 private List<String> eventLog;
7

8 public Process(int id) {


9 [Link] = id;
10 [Link] = 0;
11 [Link] = new ArrayList<>();
12 }
13

14 // Local event execution


15 public void executeLocalEvent(String eventDescription) {

2
16 logicalClock++;
17 String event = [Link]("P%d: Local Event '%s' at time %d",
18 processId,
19 eventDescription,
20 logicalClock);
21 [Link](event);
22 [Link](event);
23 }
24

25 // Send message to another process


26 public Message sendMessage(Process receiver,
27 String messageContent) {
28 logicalClock++;
29 Message msg = new Message([Link], [Link](),
30 messageContent, [Link]);
31

32 String event = [Link]("P%d: Sending message '%s'


33 to P%d at time %d", processId, messageContent,
34 [Link](), logicalClock);
35 [Link](event);
36 [Link](event);
37

38 return msg;
39 }
40

41 // Receive message from another process


42 public void receiveMessage(Message message) {
43 int receivedTimestamp = [Link]();
44 logicalClock = [Link](logicalClock, receivedTimestamp) + 1;
45

46 String event = [Link]("P%d: Received message '%s' from


47 P%d at time %d (msg timestamp: %d)", processId,
48 [Link](), [Link](),
49 logicalClock, receivedTimestamp);
50 [Link](event);
51 [Link](event);

3
52 }
53

54 // Getters
55 public int getProcessId() { return processId; }
56 public int getLogicalClock() { return logicalClock; }
57 public List<String> getEventLog() { return eventLog; }
58

59 public void displayEventLog() {


60 [Link]("\n=== Event Log for Process " +
61 processId + " ===");
62 for (String event : eventLog) {
63 [Link](event);
64 }
65 [Link]("Final Clock Value: " + logicalClock);
66 }
67 }
68

69 class Message {
70 private int senderId;
71 private int receiverId;
72 private String content;
73 private int timestamp;
74

75 public Message(int senderId,


76 int receiverId,
77 String content,
78 int timestamp) {
79 [Link] = senderId;
80 [Link] = receiverId;
81 [Link] = content;
82 [Link] = timestamp;
83 }
84

85 // Getters
86 public int getSenderId() { return senderId; }

4
87 public int getReceiverId() { return receiverId; }
88 public String getContent() { return content; }
89 public int getTimestamp() { return timestamp; }
90

91 @Override
92 public String toString() {
93 return [Link]("Message[from P%d to P%d: '%s' @ %d]",
94 senderId, receiverId, content, timestamp);
95 }
96 }
97

98 public class LamportClock {


99 public static void main(String[] args) {
100 [Link]("=== LAMPORT'S LOGICAL CLOCK
101 ALGORITHM SIMULATION ===\n");
102

103 // Create three processes


104 Process p1 = new Process(1);
105 Process p2 = new Process(2);
106 Process p3 = new Process(3);
107

108 [Link]("Simulating distributed system with


109 3 processes...\n");
110

111 // Simulate sequence of events


112

113 // Step 1: Local events


114 [Link]("Initialize database");
115 [Link]("Start computation");
116 [Link]("Load configuration");
117

118 [Link]();
119

120 // Step 2: Message communications


121 Message msg1 = [Link](p2, "Database ready");

5
122 [Link](msg1);
123

124 [Link]();
125

126 Message msg2 = [Link](p3, "Begin processing");


127 [Link](msg2);
128

129 [Link]();
130

131 // Step 3: More local events


132 [Link]("Update records");
133 [Link]("Process data");
134

135 [Link]();
136

137 // Step 4: Concurrent messages


138 Message msg3 = [Link](p1, "Processing complete");
139 Message msg4 = [Link](p1, "Computation finished");
140

141 [Link](msg3);
142 [Link](msg4);
143

144 [Link]();
145

146 // Step 5: Final local events


147 [Link]("Generate report");
148 [Link]("Cleanup resources");
149 [Link]("Save results");
150

151 // Display complete event logs


152 [Link]("\n" + "=".repeat(60));
153 [Link]("COMPLETE EVENT LOGS");
154 [Link]("=".repeat(60));
155

156 [Link]();

6
157 [Link]();
158 [Link]();
159

160 // Display timeline analysis


161 displayTimelineAnalysis(p1, p2, p3);
162 }
163

164 private static void displayTimelineAnalysis(Process... processes) {


165 [Link]("\n" + "=".repeat(60));
166 [Link]("TIMELINE ANALYSIS");
167 [Link]("=".repeat(60));
168

169 // Collect all events with their timestamps


170 List<EventInfo> allEvents = new ArrayList<>();
171

172 for (Process p : processes) {


173 for (String event : [Link]()) {
174 // Extract timestamp from event string
175 String[] parts = [Link](" at time ");
176 if ([Link] == 2) {
177 int timestamp = [Link](parts[1].split(" ")[0]);
178 [Link](new EventInfo([Link](),
179 event, timestamp));
180 }
181 }
182 }
183

184 // Sort events by timestamp, then by process ID for tie-breaking


185 [Link]((a, b) -> {
186 if ([Link] != [Link]) {
187 return [Link]([Link], [Link]);
188 }
189 return [Link]([Link], [Link]);
190 });
191

7
192 // Display chronological order
193 [Link]("Events in Logical Time Order:");
194 [Link]("-".repeat(80));
195 for (EventInfo event : allEvents) {
196 [Link]("Time %d: %s%n",
197 [Link],
198 [Link]);
199 }
200

201 [Link]("\nFinal Clock Values:");


202 for (Process p : processes) {
203 [Link]("Process %d: %d%n",
204 [Link](),
205 [Link]());
206 }
207 }
208

209 // Helper class for timeline analysis


210 static class EventInfo {
211 int processId;
212 String description;
213 int timestamp;
214

215 EventInfo(int processId, String description,


216 int timestamp) {
217 [Link] = processId;
218 [Link] = description;
219 [Link] = timestamp;
220 }
221 }
222 }

5. Output

8
9
6. Discussion
This lab involved implementing Lamport’s Logical Clock Algorithm in Java to simulate
the ordering of events in a distributed system. Through this exercise, we observed how
logical clocks enable coordination between processes without relying on physical time syn-
chronization. Each process in the simulation maintained its own logical clock, incrementing
it during internal events and message exchanges. The experiment clearly demonstrated the
importance of updating logical clocks based on received timestamps to maintain causal con-
sistency. Events were successfully timestamped and ordered in a way that preserved the
“happened-before” relationship.

7. Conclusion
In conclusion, this lab on implementation and analysis of Lamport’s Logical Clock Algorithm
reinforced the theoretical understanding of event ordering in distributed systems. This lab
underscored the significance of logical time in managing distributed processes, particularly
in environments where global time consensus is infeasible

10

You might also like