Program for page replacement algorithm in java



In operating systems that use paging for memory management, page replacement algorithm are needed to decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to reduce number of page faults.
In Least Recently Used (LRU) algorithm is a Greedy algorithm where the page to be replaced is least recently used. The idea is based on locality of reference, the least recently used page is not likely
Let say the page reference string 7 0 1 2 0 3 0 4 2 3 0 3 2 . Initially we have 4 page slots empty.
Initially all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4 Page faults
0 is already their so —> 0 Page fault.
when 3 came it will take the place of 7 because it is least recently used —>1 Page fault
0 is already in memory so —> 0 Page fault.
4 will takes place of 1 —> 1 Page Fault
Now for the further page reference string —> 0 Page fault because they are already available in the memory.

program in java



import java.util.*;
class lru
{
public static void main(String ar[])
{
int[] a =new int[5];
int[] b =new int[20];
int n,p=0,q=0,m=0,h,k,i,s=0,g=0,j,u;
String f;
f="fault";
System.out.println("enter the no of pages");
Scanner in =new Scanner(System.in);
n=in.nextInt();
System.out.println("enter the page no");
for(i=0;i<n;i++)
{
b[i]=in.nextInt();
}
             for(i=0;i<n;i++)
  {
if(p==0)
{
if(q>=3)
{
q=0;
}
a[q]=b[i];
q++;
if(s<3)
{
s=q;
}
}
  
System.out.print(b[i]);
System.out.print("\t");
for(h=0;h<s;h++)
{
System.out.print("\t"+a[h]);
}
if((p==0)&&(q<=3))
{
System.out.print("\t---->"+f);
            m++;
}
System.out.print("\n\n");
               p=0;
   g=0;
   if(s==3)
   {
   
              for(k=0;k<s;k++)
                {
                  if(b[i+1]==a[k])
  {
                   p=1;
  }
}
for(j=0;j<s;j++)
{
u=0;
k=i;
while(k>=(i-1)&&(k>=0))
{
if(b[k]==a[j])
u++;
k--;
}
if(u==0)
q=j;
}
   }
   else
   {
   for(k=0;k<q;k++)
   {
   if(b[i+1]==a[k])
   p=1;
   }
   }
  }
  
           System.out.println("total no of faults  = "+m);
}
}

output

if any problem in program pls write email on js2926803@gmail.com
pls like share to ur frnd 
and comment that which program u want in java or any rogramming languages

Comments