×

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

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.