×

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

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

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

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

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

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.