Saturday, April 19, 2014

Here's a simulation of Least Recently Used algorithm for page replacement . . .Tell me if any Changes required . ..

LRU.java

import java.util.Scanner;
public class LRU
{
public static void main(String[] args)
{
System.out.println("Enter the Number of Frames : ");
Scanner sc = new Scanner(System.in);
int F = sc.nextInt();
Page page[] = new Page[F];
int pages[] = new int[100]; // Array of String References
for(int i =0;i<F;i++)
{
page[i] = new Page(F);
}
int min=0,i=0;
System.out.println("Enter the Page no (0 for exit)");
//Entering the String References...
while(true)
{
int x = sc.nextInt();
if(x==0) break;
else
pages[i++] = x;
}
// Now Applying the LRU Strategy
boolean pageFaultOccured = true;
for(int j=0; j<i; j++)
{
for(int k=0;k<F;k++)
{
if(page[k].pno == pages[j]) // do we have requested page in memory?
{
pageFaultOccured = false;
page[k].set();
break;
}
}
if(pageFaultOccured == false)
{
pageFaultOccured = true;
System.out.println("NO PAGE FAULT");
for(int k=0;k<F && page[k].count!=F;k++)
{
page[k].dec();
}
}
else
{
System.out.println("PAGE FAULT");
// now find which page need to be replaced
// Find a page with minimum count value (least used)
for(int l=0; l<3; l++)
{
if(page[min].count>page[l].count)
min=l;

page[l].dec();
}
page[min].pno = pages[j];
System.out.println("Page entered at Frame : "+min);
page[min].set();
}
}
}
}
class Page
{
int pno;
int count;
int Frames;
Page(int Frames)
{
this.pno = 0;
this.count = 0;
this.Frames = Frames;
}
void dec()
{
if(this.count == 0)
this.count = 0;
else
this.count--;
}
void set()
{
this.count = this.Frames;
}

}


No comments:

Post a Comment