×

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

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 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.

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.