×

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes, we need specific election methods like bully and ring.

The processes that serve as supervisors are chosen using election algorithms as a single process. When the selected coordinator process crashes for some reason, a new process is selected. The selection algorithms are used to decide the location where the fresh copy of the coordinator must be restarted.

It is assumed that every process in the system has a specific priority number and that the primary priority process would be selected as the new coordinator first. In the event that the current usage coordinator process fails, a new process with the main priority number is chosen. We note that priority number and give it to each running distributed system process.

The following is the Bully election algorithm:

Assume P is a coordinator-sending process that transmits messages.

  • When the coordinator doesn't respond within the time interval T, it will assume that the coordinator procedure has failed.
  • Process P will send the main priority number and an election message to all running processes.
  • In the current method, P will choose itself as a supervisor if it doesn't hear back within the time period T.
  • After choosing itself to be the coordinator, it notifies any processes with lower priority that process P has been selected as their new coordinator.
  • If process P gets a response from the other processes Q within time T, then it has been chosen as the coordinator by process Q and must wait for time T to obtain another response.
  • It is believed to have failed, and the process is repeated if it fails to receive a reaction within time T.

BullyAlgo.java

import java.io.*;  
import java.util.Scanner;  
// importing the packages 
// To comprehend how bullying algorithms function, create the class BullyAlgoExample.  
class BullyAlgo{  
      
    // Regarding the process and its status, declare variables and arrays. 
static int noofprocess;  
static int priority[] = newint[100];  
static int S[] = newint[100];  
static int C;  
  
    // main() method of the class  
public static void main(String args[]) throws IOException    
    {  
    // Taking input for the number of processes from the user  
System. out.println("Select the no.of process that are to be done:");  
  
        // Object creation for scanner class  
        Scanner sc = new Scanner(System.in);  
        noofprocess = sc.nextInt();  
  
int i;  
  
        // Setting priorities for the process in the for loop  
for(i = 0; i<noofprocess; i++)  
        {  
System.out.println("Status for process "+(i+1)+":");  
S[i] = sc.nextInt();  
System.out.println("Priority of the current process "+(i+1)+":");  
priority[i] = sc.nextInt();  
        }  
  
System.out.println("Which process have to be elected for initation :");  
int e = sc.nextInt();  
  
sc.close();  
  
        // call electProcess() method   
electProcess(e);  
System.out.println("After electing process the final coordinator is "+C);  
    }  
  
    // create electProcess() method   
static void electProcess(int e)  
    {  
e = e - 1;  
C = e + 1;  
  
for(int i = 0; i<noofprocess; i++)  
        {  
    if(priority[e]<priority[i])  
            {  
System.out.println("Election message is sent from "+(e+1)+" to "+(i+1));  
if(S[i]==1)  
    electProcess(i+1);  
            }  
        }  
    }  
}  

BullyAlgo2.java

// Importing the packages
import java.util.Scanner;  
  


class Process{  
      
    public int pid;  
    public StRound status;  
      
     
    public Process(int pid){  
        this.pid = pid;  
        this.status = "active";  
    }  
}  


public class BullyAlgo {  
      
    
    Scanner sc;  
    Process[] Process;  
    int num;  
      
      
    public BullyAlgoExample2(){  
        sc= new Scanner(System.in);  
    }  
      


   
    publicvopid Round(){  
          
          
        System.out.println("Enter total number of Process of Process");  
        num = sc.nextInt();  
          
         
        Process = new Process[n];  
        for(int j = 0; j< num; j++){  
            Process[j]= new Process(j);  
        }  
    }  
      
    
    publicvopidperformElection(){  
  
        
        try {  
            Thread.sleep(100);  
        } catch (InterruptedException ae) {  
              
            ae.printStackTrace();  
        }  
          
         
        System.out.println("Process having pid "+Process[getMaxValue()].pid+" fails");  
          
          
        Process[getMaxValue()].status = "Inactive";  
          
         
        int currentpid = 0;  
        boolean oversts = true;  
          
       
        while(oversts){  
              
            boolean high = false;  
              
             
            for(int i = currentpid + 1; i< n; i++){  
                if(Process[i].status == "active"){  
                    System.out.println("Process "+currentpid+" Passes Election("+currentpid+") message to process" +i);  
                    high = true;  
  
                }  
            }  
              
           
            if(high){  
                  
                
                for(int i = currentpid + 1; i< n; i++){  
                    if(Process[i].status == "active"){  
                        System.out.println("Process "+i+"Passes Ok("+i+") message to process" +currentpid);  
                    }  
  
                }  
                 
                currentpid++;  
            }  
  
            else{  
                
                int cod = Process[getMaxValue()].pid;  
                  
                 
                System.out.println("Finally Process "+cod+" Becomes codinator");  
                  
                  
                for(int i = cod - 1; i>= 0; i--){  
                    if(Process[i].status == "active"){  
                        System.out.println("Process "+cod+"Passes codinator("+cod+") message to process " +i);  
                    }  
                }  
                  
                  
                System. out.println("End of Election");  
                oversts = false;  
                break;  
            }  
        }  
  
    }  
      
 
    public int getMaxValue(){  
        int  Maxpid = -99;  
        int Maxpidin = 0;  
        for(inti = 0; i<Process.length; i++){  
            if(Process[i].status == "active" && Process[i].pid >Maxpid){  
                Maxpid = Process[i].pid;  
                Maxpidin = i;  
            }  
        }  
        return Maxpidin;  
    }  
      
   
    publicstaticvopid main(StRound[] args) {  
          
       
        BullyAlgoExample2 bully = newBullyAlgoExample2();  
          
       
        bully.Round();  
        bully.performElection();  
  
    }  
  
}  

Output:

Bully Algorithm code in Java

Related Topics

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.