Search Here

Java program for Deadlock handling using Banker’s algorithm


/* Bankers Algorithm */
    
import java.util.Scanner;
public class Bankers
{
    private int NEED[][],ALLOCATE[][],MAX[][],AVAILABLE[][],np,nr;
     
    private void input()
    {
  Scanner sc=new Scanner(System.in);
  
  System.out.print("Enter no. of Processes: ");
  np=sc.nextInt();
  System.out.print("Enter no. of Resources: ");
  nr=sc.nextInt();
  
  NEED=new int[np][nr];     /* Initializing NEED Matrix */
  MAX=new int[np][nr];      /* Initializing MAX Matrix */ 
  ALLOCATE=new int[np][nr]; /* Initializing ALLOCATION Matrix */
  AVAILABLE=new int[1][nr]; /* Initializing AVAILABLEABLE Matrix */

  System.out.println("\nEnter ALLOCATION matrix: ");
  for(int i=0;i<np;i++)
   for(int j=0;j<nr;j++)
     ALLOCATE[i][j]=sc.nextInt(); 

  System.out.println("\nEnter MAX matrix: ");
  for(int i=0;i<np;i++)
     for(int j=0;j<nr;j++)
     MAX[i][j]=sc.nextInt();

  System.out.println("\nEnter AVAILABLE matrix: ");
  for(int j=0;j<nr;j++)
    AVAILABLE[0][j]=sc.nextInt();
  sc.close();
 }
     
    private int[][] calc_NEED()
    {
        for(int i=0;i<np;i++)
          for(int j=0;j<nr;j++)  /* Calculating NEED matrix */
            NEED[i][j]=MAX[i][j]-ALLOCATE[i][j];
       return NEED;
    }
  
    private boolean check(int i)
    {
       /* Checking whether all resources for ith process can be allocated or not */
        for(int j=0;j<nr;j++) 
         if(AVAILABLE[0][j]<NEED[i][j])
            return false;
     return true;
    }
 
    public void saftyAlgo()
    {
       input();
       calc_NEED();
       boolean done[]=new boolean[np];
       int j=0;
 
       while(j<np) /* Until all process are allocated */
       {  
         boolean allocated=false;
         for(int i=0;i<np;i++)
         if(!done[i] && check(i)) /* Trying to allocate */
         {  
          for(int k=0;k<nr;k++)
              AVAILABLE[0][k]=AVAILABLE[0][k]-NEED[i][k]+MAX[i][k];
           System.out.println("\tAllocated process : "+i);
           allocated=done[i]=true;
             j++;
         }
         if(!allocated) 
          break;  //if no allocation
       }
       if(j==np)  //if all processes are allocated
         System.out.println("\nSafely Allocated");
       else
         System.out.println("All Proceess can not be allocated safely");
    }
     
    public static void main(String[] args) 
    {
       new Bankers().saftyAlgo();
    }
}

JAVA program for deadlock handling using Banker’s algorithm
Output

No comments:

Post a Comment