Banker’s Algorithm Simulation in Java Programming language with the help of example

In this article Banker’s algorithm is explain with the help of example and codding implementation in Java programming language. The Banker’s algorithm is an algorithm developed for resource allocation and to avoid deadlocks in Operating system.
The Banker’s algorithm is run on the operating system to determine whether a state is safe or not. Operating System can have multiple resources and processes. Only if a state of process is safe then deadlock would not happen otherwise the deadlock is happened.In banker’s algorithm three condition is must satisfied to work the banker’s algorithm. Algorithm at first check the currently running processes whether they can acquire their marked maximum resources or not from the currently available resources. In algorithm processes is run in sequential only. After finishing a processes other processes is started. After finishing the processes process release there used resources.
If any of the process fails to achieve its maximum resources the state would be considered as unsafe and method return the 0 value.
In our implementation one method is used which will return 0 in case the state is safe otherwise in case of the state is unsafe , it will return first process number which fails to get maximum resources.Coding:-
Abbreviation used in this program (code) is where
allocatedResouses, maximumResources, availableResources are defining the currently allocated resources to processes, maximum resources which can used by processes and available resources that can use by processes respectively.

public class BankersAlgoSimulation 
{ 
public int getStateStatus( 
int allocatedResouses[][],int maximumResources[][],
int availableResources[])
{ 
int number = availableResources.length ; 
int ResourceA = allocatedResources.length;
int i,j,k;int flagVar=0; 
for(i=0;i<ResourceA;i++)
{ 
for(j=0;j<number;j++)
{ 
if( maximumResources[i][j]-allocatedResouses[i][j]
>availableResources[j])
{
flagVar=1;return i 1;
}
} 
for(k=0;k<number;k++)
{
availableResources[k]= allocatedResouses[i][k] availableResources[k];
}
}
return flagVar;}
public static void main(String args[])
{BankersAlgoSimulation bobj=new BankersAlgoSimulation();

int availableresources[]={3,1,1,2};

int allocatedresources[][]={ {1,2,2,1},{1,1,3,3},{1,1,1,0},{3,2,1,1}};

int maximumresources[][]={ {3,3,2,2},{1,7,3,4},{1,1,5,0},{2,2,3,3}};

int resources=bobj.getStateStatus
(allocatedresources, maximumresources , availableresources );
if(resources==0)
{ 
System.out.println("The state is in 
safe mode and no deadlock happened");
}
else
{ 
System.out.println("The process no "  resources " is fails to safe");
}
} 
}
Output of banker's algorithm

Output of banker's algorithm

One Response
  1. December 27, 2012