0% found this document useful (0 votes)
2 views2 pages

Bully Algorithm Java Code

The document presents a Java implementation of the Bully Algorithm for electing a coordinator in a distributed system. It allows users to crash and recover processes, displaying the current coordinator and initiating elections when necessary. The program continuously prompts for user input to manage process states and elections.

Uploaded by

Vighnesh Sawant
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)
2 views2 pages

Bully Algorithm Java Code

The document presents a Java implementation of the Bully Algorithm for electing a coordinator in a distributed system. It allows users to crash and recover processes, displaying the current coordinator and initiating elections when necessary. The program continuously prompts for user input to manage process states and elections.

Uploaded by

Vighnesh Sawant
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

Bully Algorithm in Distributed System (Java Code)

import [Link].*;

class BullyAlgorithm {
static int n, coordinator;
static boolean[] active;

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter number of processes: ");


n = [Link]();

active = new boolean[n + 1];

for (int i = 1; i <= n; i++) {


active[i] = true;
}

coordinator = n; // highest process is coordinator


[Link]("Current Coordinator is: " + coordinator);

while (true) {
[Link]("\n1. Crash a process");
[Link]("2. Recover a process");
[Link]("3. Display Coordinator");
[Link]("4. Exit");
[Link]("Enter choice: ");
int choice = [Link]();

switch (choice) {
case 1:
[Link]("Enter process to crash: ");
int crash = [Link]();
active[crash] = false;
[Link]("Process " + crash + " crashed.");
if (crash == coordinator) {
election(crash);
}
break;

case 2:
[Link]("Enter process to recover: ");
int recover = [Link]();
active[recover] = true;
[Link]("Process " + recover + " recovered.");
election(recover);
break;

case 3:
[Link]("Current Coordinator is: " + coordinator);
break;

case 4:
[Link](0);
}
}
}

static void election(int initiator) {


[Link]("Election initiated by process " + initiator);
coordinator = initiator;

for (int i = initiator + 1; i <= n; i++) {


if (active[i]) {
[Link]("Process " + i + " responds.");
election(i);
return;
}
}

[Link]("Process " + coordinator + " becomes new coordinator.");


}
}

You might also like