Least Recently Used page replacement algorithm (LRU) program in java

In Least Recently Used page replacement algorithm (LRU) we use the recent past as an approximation of the near future,then we will replace the pagethat has not been used for the longest period of time.
In Least Recently Used page replacement algorithm (LRU) is associated with the each page the time of that page's last use.When a page must be replaced,In Least Recently Used page replacement algorithm (LRU) chooses that page has not been used for longest period of time.The In Least Recently Used page replacement algorithm (LRU) Policy is often used as page replacement algorithm and is consider to be good.The major problem is how to implement In Least Recently Used page replacement algorithm (LRU).An In Least Recently Used page replacement algorithm (LRU) may require substantial hardware assistance.


import java.io. * ;
class LRU {
	public static int sort(int c[]) {
		int max = -1;
		int temp = -1;
		for (int k = 0; k < 3; k++) {
			if (c[k] > max) {
				max = c[k];
				temp = k;
			}
		}
		return temp;
	}
	public static void main(String args[]) throws IOException {
		int z,
		m = 0,
		hit = 0,
		faults = 0;
		InputStreamReader isr = new InputStreamReader(System. in );
		BufferedReader br = new BufferedReader(isr);
		System.out.println("enter the size of the array");
		int n = Integer.parseInt(br.readLine());
		int a[] = new int[n];
		int flag[] = new int[n];
		System.out.println("enter the elements");
		for (int i = 0; i < n; i++) {
			a[i] = Integer.parseInt(br.readLine());
			flag[i] = 0;
		}
		int b[] = new int[3];
		int c[] = new int[3];
		for (int i = 0; i < 3; i++) {
			b[i] = -1;
			c[i] = 0;
		}
		for (int i = 0; i < n; i++) {
			z = a[i];
			for (int j = 0; j < 3; j++) {
				if (z == b[j]) {
					flag[i] = 1;
					hit = hit + 1;
					break;
				}
			}
			if (flag[i] == 0 && b[2] == -1) {
				for (int j = 0; j < 3; j++) {
					if (b[j] == -1) {
						b[j] = z;
						faults = faults + 1;
						flag[i] = 1;
						break;
					}
				}
			}
			if (flag[i] == 0) {
				m = sort(c);
				b[m] = z;
				faults = faults + 1;
				flag[i] = 1;
				for (int k = 0; k < 3; k++)
				c[k] = c[k] + 1;
				c[m] = 0;
			}
		}
		System.out.println("no of hits" + hit);
		System.out.println("no of faults" + faults);
		System.out.println("hit ratio" + (hit * 100) / (hit + faults));

	}
}

/*Least Recently Used page replacement algorithm (LRU) output:

enter the size of the array
10

enter the elements
2 3 5 4 2 5 7 3 8 7

no of hits 2
no of faults 8
hit ratio 20
*/

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *