-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBullyAlgorithm.java
More file actions
61 lines (50 loc) · 2 KB
/
BullyAlgorithm.java
File metadata and controls
61 lines (50 loc) · 2 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
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class BullyAlgorithm {
static final int N = 5;
static final int WAIT = 2000;
static int coordinator = -1;
static class Process {
int id;
boolean isUp = true;
Process(int id) { this.id = id; }
void startElection(List<Process> all) {
if (!isUp) return;
System.out.println("P" + id + " starts election...");
boolean higherAlive = false;
for (Process p : all)
if (p.id > id && p.isUp) {
System.out.println("P" + id + " → ELECTION → P" + p.id);
higherAlive = true;
}
if (!higherAlive) becomeCoordinator(all);
else {
try { Thread.sleep(WAIT); } catch (Exception ignored) {}
if (coordinator == -1 || !all.get(coordinator - 1).isUp)
becomeCoordinator(all);
}
}
void becomeCoordinator(List<Process> all) {
coordinator = id;
System.out.println("\nP" + id + " becomes COORDINATOR");
for (Process p : all)
if (p.id != id && p.isUp)
System.out.println("P" + p.id + " acknowledges new coordinator " + id);
}
}
public static void main(String[] args) throws InterruptedException {
List<Process> procs = new ArrayList<>();
for (int i = 1; i <= N; i++) procs.add(new Process(i));
coordinator = N;
System.out.println("Initial Coordinator: P" + coordinator);
// Simulate random coordinator crash
Thread.sleep(2000);
Process crashed = procs.get(coordinator - 1);
crashed.isUp = false;
System.out.println("\nP" + crashed.id + " (Coordinator) crashed!");
// Start election from lowest process
procs.get(0).startElection(procs);
Thread.sleep(1000);
System.out.println("\nFinal Coordinator: P" + coordinator);
}
}