-
Notifications
You must be signed in to change notification settings - Fork 696
/
Bankers.java
122 lines (109 loc) · 2.15 KB
/
Bankers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
public class Bankers
{
int n = 5; // Number of processes
int m = 3; // Number of resources
int need[][] = new int[n][m];
int [][]max;
int [][]alloc;
int []avail;
int safeSequence[] = new int[n];
void initializeValues()
{
// P0, P1, P2, P3, P4 are the Process names here
// Allocation Matrix
alloc = new int[][] { { 0, 1, 0 }, //P0
{ 2, 0, 0 }, //P1
{ 3, 0, 2 }, //P2
{ 2, 1, 1 }, //P3
{ 0, 0, 2 } }; //P4
// MAX Matrix
max = new int[][] { { 7, 5, 3 }, //P0
{ 3, 2, 2 }, //P1
{ 9, 0, 2 }, //P2
{ 2, 2, 2 }, //P3
{ 4, 3, 3 } }; //P4
// Available Resources
avail = new int[] { 3, 3, 2 };
}
void isSafe()
{
int count=0;
//visited array to find the already allocated process
boolean visited[] = new boolean[n];
for (int i = 0;i < n; i++)
{
visited[i] = false;
}
//work array to store the copy of available resources
int work[] = new int[m];
for (int i = 0;i < m; i++)
{
work[i] = avail[i];
}
while (count<n)
{
boolean flag = false;
for (int i = 0;i < n; i++)
{
if (visited[i] == false)
{
int j;
for (j = 0;j < m; j++)
{
if (need[i][j] > work[j])
break;
}
if (j == m)
{
safeSequence[count++]=i;
visited[i]=true;
flag=true;
for (j = 0;j < m; j++)
{
work[j] = work[j]+alloc[i][j];
}
}
}
}
if (flag == false)
{
break;
}
}
if (count < n)
{
System.out.println("The System is UnSafe!");
}
else
{
//System.out.println("The given System is Safe");
System.out.println("Following is the SAFE Sequence");
for (int i = 0;i < n; i++)
{
System.out.print("P" + safeSequence[i]);
if (i != n-1)
System.out.print(" -> ");
}
}
}
void calculateNeed()
{
for (int i = 0;i < n; i++)
{
for (int j = 0;j < m; j++)
{
need[i][j] = max[i][j]-alloc[i][j];
}
}
}
public static void main(String[] args)
{
int i, j, k;
Bankers gfg = new Bankers();
gfg.initializeValues();
//Calculate the Need Matrix
gfg.calculateNeed();
// Check whether system is in safe state or not
gfg.isSafe();
}
}