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

Lamport Algorithm

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)
4 views10 pages

Lamport Algorithm

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
You are on page 1/ 10

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
LamportClock.java

1 import java.util.*;
2

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

8 public Process(int id) {


9 this.processId = id;
10 this.logicalClock = 0;
11 this.eventLog = new ArrayList<>();
12 }
13

14 // Local event execution


15 public void executeLocalEvent(String eventDescription) {

2
16 logicalClock++;
17 String event = String.format("P%d: Local Event '%s' at time %d",
18 processId,
19 eventDescription,
20 logicalClock);
21 eventLog.add(event);
22 System.out.println(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(this.processId, receiver.getProcessId(),
30 messageContent, this.logicalClock);
31

32 String event = String.format("P%d: Sending message '%s'


33 to P%d at time %d", processId, messageContent,
34 receiver.getProcessId(), logicalClock);
35 eventLog.add(event);
36 System.out.println(event);
37

38 return msg;
39 }
40

41 // Receive message from another process


42 public void receiveMessage(Message message) {
43 int receivedTimestamp = message.getTimestamp();
44 logicalClock = Math.max(logicalClock, receivedTimestamp) + 1;
45

46 String event = String.format("P%d: Received message '%s' from


47 P%d at time %d (msg timestamp: %d)", processId,
48 message.getContent(), message.getSenderId(),
49 logicalClock, receivedTimestamp);
50 eventLog.add(event);
51 System.out.println(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 System.out.println("\n=== Event Log for Process " +
61 processId + " ===");
62 for (String event : eventLog) {
63 System.out.println(event);
64 }
65 System.out.println("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 this.senderId = senderId;
80 this.receiverId = receiverId;
81 this.content = content;
82 this.timestamp = 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 String.format("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 System.out.println("=== 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 System.out.println("Simulating distributed system with


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

111 // Simulate sequence of events


112

113 // Step 1: Local events


114 p1.executeLocalEvent("Initialize database");
115 p2.executeLocalEvent("Start computation");
116 p3.executeLocalEvent("Load configuration");
117

118 System.out.println();
119

120 // Step 2: Message communications


121 Message msg1 = p1.sendMessage(p2, "Database ready");

5
122 p2.receiveMessage(msg1);
123

124 System.out.println();
125

126 Message msg2 = p2.sendMessage(p3, "Begin processing");


127 p3.receiveMessage(msg2);
128

129 System.out.println();
130

131 // Step 3: More local events


132 p1.executeLocalEvent("Update records");
133 p3.executeLocalEvent("Process data");
134

135 System.out.println();
136

137 // Step 4: Concurrent messages


138 Message msg3 = p3.sendMessage(p1, "Processing complete");
139 Message msg4 = p2.sendMessage(p1, "Computation finished");
140

141 p1.receiveMessage(msg3);
142 p1.receiveMessage(msg4);
143

144 System.out.println();
145

146 // Step 5: Final local events


147 p1.executeLocalEvent("Generate report");
148 p2.executeLocalEvent("Cleanup resources");
149 p3.executeLocalEvent("Save results");
150

151 // Display complete event logs


152 System.out.println("\n" + "=".repeat(60));
153 System.out.println("COMPLETE EVENT LOGS");
154 System.out.println("=".repeat(60));
155

156 p1.displayEventLog();

6
157 p2.displayEventLog();
158 p3.displayEventLog();
159

160 // Display timeline analysis


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

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


165 System.out.println("\n" + "=".repeat(60));
166 System.out.println("TIMELINE ANALYSIS");
167 System.out.println("=".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 : p.getEventLog()) {
174 // Extract timestamp from event string
175 String[] parts = event.split(" at time ");
176 if (parts.length == 2) {
177 int timestamp = Integer.parseInt(parts[1].split(" ")[0]);
178 allEvents.add(new EventInfo(p.getProcessId(),
179 event, timestamp));
180 }
181 }
182 }
183

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


185 allEvents.sort((a, b) -> {
186 if (a.timestamp != b.timestamp) {
187 return Integer.compare(a.timestamp, b.timestamp);
188 }
189 return Integer.compare(a.processId, b.processId);
190 });
191

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

201 System.out.println("\nFinal Clock Values:");


202 for (Process p : processes) {
203 System.out.printf("Process %d: %d%n",
204 p.getProcessId(),
205 p.getLogicalClock());
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 this.processId = processId;
218 this.description = description;
219 this.timestamp = 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