×

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

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.