If you are not familiar with Least Recently Used Algorithm, check Least Recently Used Algorithm(Page Replacement)
This algorithm is a combination of using a queue, similar to FIFO (FIFO (Page Replacement)) alongside using an array to keep track of the bits used to give the queued page a “second chance”.
How does the algorithm work:
- Set all the values of the bitref as False (Let it be the size of max capacity of queue).
- Set an empty queue to have a max capacity.
- Check if the queue is not full:
- If the element is in the queue, set its corresponding bitref = 1.
- If the element is not in the queue, then push it into the queue.
- If the queue is full:
- Find the first element of the queue that has its bitref = 0 and if any element in the front has bitref = 1, set it to 0. Rotate the queue until you find an element with bitref = 0.
- Remove that element from the queue.
- Push the current element from the input array into the queue.
Explanation: The bits are set as usual in this case to one for the indices in the bitref until the queue is full. Once the queue becomes full, according to FIFO Page Replacement Algorithm, we should get rid of the front of the queue (if the element is a fault/miss). But here we don’t do that. Instead we first check its reference bit (aka bitref) if its 0 or 1 (False or True). If it is 0 (false), we pop it from the queue and push the waiting element into the queue. But if it is 1 (true), we then set its reference bit (bitref) to 0 and move it to the back of the queue. We keep on doing this until we come across the front of the queue to have its front value’s reference bit (bitref) as 0 (false). Then we follow the usual by removing it from the queue and pushing the waiting element into the queue. What if the waiting element is in the queue already? We just set its reference bit (bitref) to 1 (true).
We now move all the values like 2, 4, 1 to the back until we encounter 3, whose bitref is 0. While moving 2, 4, 1 to the back, we set their bitref values to 0.
So now, the question how is this an approximation of LRU, when it clearly implements FIFO instead of LRU. Well, this works by giving a second chance to the front of the queue (which in FIFO‘s case would have been popped and replaced). Here, the second chance is based on the fact that if the element is seen “recently” its reference bit (bitref) is set to 1 (true). If it was not seen recently, we would not have set its reference bit (bitref) to 1 (true) and thus removed it. Hence, this is why, it is an approximation and not LRU nor FIFO.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
bool findQueue(queue<int> q, int x)
{
while (!q.empty()) {
if (x == q.front())
return true;
q.pop();
}
return false;
}
void LRU_Approximation(vector<int> t, int capacity)
{
int n = t.size();
queue<int> q;
int hits = 0, faults = 0;
bool bitref[capacity] = { false };
int ptr = 0;
int count = 0;
for (int i = 0; i < t.size(); i++) {
if (!findQueue(q, t[i])) {
if (count < capacity) {
q.push(t[i]);
count++;
}
else {
ptr = 0;
while (!q.empty()) {
if (bitref[ptr % capacity])
bitref[ptr % capacity] = !bitref[ptr % capacity];
else
break;
ptr++;
}
if (q.empty()) {
q.pop();
q.push(t[i]);
}
else {
int j = 0;
while (j < (ptr % capacity)) {
int t1 = q.front();
q.pop();
q.push(t1);
bool temp = bitref[0];
for (int counter = 0; counter < capacity - 1; counter++)
bitref[counter] = bitref[counter + 1];
bitref[capacity - 1] = temp;
j++;
}
q.pop();
q.push(t[i]);
}
}
faults++;
}
else {
queue<int> temp = q;
int counter = 0;
while (!q.empty()) {
if (q.front() == t[i])
bitref[counter] = true;
counter++;
q.pop();
}
q = temp;
hits++;
}
}
cout << "Hits: " << hits << "\nFaults: " << faults << '\n';
}
int main()
{
vector<int> t = { 2, 3, 2, 1, 5, 2, 4, 5, 3, 2, 5, 2 };
int capacity = 4;
LRU_Approximation(t, capacity);
return 0;
}
|
Java
import java.util.*;
public class Main {
static boolean findQueue(Queue<Integer> q, int x) {
for (int i : q) {
if (x == i)
return true;
}
return false;
}
static void LRU_Approximation(List<Integer> t, int capacity) {
int n = t.size();
Queue<Integer> q = new LinkedList<>();
int hits = 0, faults = 0;
boolean[] bitref = new boolean[capacity];
int ptr = 0;
int count = 0;
for (int i = 0; i < t.size(); i++) {
if (!findQueue(q, t.get(i))) {
if (count < capacity) {
q.add(t.get(i));
count++;
}
else {
ptr = 0;
while (!q.isEmpty()) {
if (bitref[ptr % capacity])
bitref[ptr % capacity] = !bitref[ptr % capacity];
else
break;
ptr++;
}
if (q.isEmpty()) {
q.poll();
q.add(t.get(i));
}
else {
int j = 0;
while (j < (ptr % capacity)) {
int t1 = q.peek();
q.poll();
q.add(t1);
boolean temp = bitref[0];
for (int counter = 0; counter < capacity - 1; counter++)
bitref[counter] = bitref[counter + 1];
bitref[capacity - 1] = temp;
j++;
}
q.poll();
q.add(t.get(i));
}
}
faults++;
}
else {
Queue<Integer> temp = new LinkedList<>(q);
int counter = 0;
while (!q.isEmpty()) {
if (q.peek() == t.get(i))
bitref[counter] = true;
counter++;
q.poll();
}
q = temp;
hits++;
}
}
System.out.println("Hits: " + hits + "\nFaults: " + faults);
}
public static void main(String[] args) {
List<Integer> t = Arrays.asList(2, 3, 2, 1, 5, 2, 4, 5, 3, 2, 5, 2);
int capacity = 4;
LRU_Approximation(t, capacity);
}
}
|
Python3
from collections import deque
def LRU_Approximation(t, capacity):
n = len(t)
q = deque()
hits = 0
faults = 0
bitref = [False] * capacity
ptr = 0
count = 0
for i in range(n):
if t[i] not in q:
if count < capacity:
q.append(t[i])
count += 1
else:
ptr = 0
while q:
if bitref[ptr % capacity]:
bitref[ptr % capacity] = not bitref[ptr % capacity]
else:
break
ptr += 1
if not q:
q.popleft()
q.append(t[i])
else:
j = 0
while j < (ptr % capacity):
t1 = q.popleft()
q.append(t1)
temp = bitref[0]
for counter in range(capacity - 1):
bitref[counter] = bitref[counter + 1]
bitref[capacity - 1] = temp
j += 1
q.popleft()
q.append(t[i])
faults += 1
else:
temp = q.copy()
counter = 0
while q:
if q[0] == t[i]:
bitref[counter] = True
counter += 1
q.popleft()
q = temp
hits += 1
print("Hits:", hits)
print("Faults:", faults)
t = [2, 3, 2, 1, 5, 2, 4, 5, 3, 2, 5, 2]
capacity = 4
LRU_Approximation(t, capacity)
|
Javascript
function findQueue(q, x)
{
while (q.length > 0) {
if (x == q[0])
return true;
q.shift();
}
return false;
}
function LRU_Approximation(t, capacity)
{
let n = t.length;
let q = [];
let hits = 0, faults = 0;
let bitref = new Array(capacity);
for(let i = 0; i < capacity; i++){
bitref[i] = false;
}
let ptr = 0;
let count = 0;
for (let i = 0; i < t.length; i++) {
if (!findQueue(q, t[i])) {
if (count < capacity) {
q.push(t[i]);
count++;
}
else {
ptr = 0;
while (q.length > 0) {
if (bitref[ptr % capacity])
bitref[ptr % capacity] = !bitref[ptr % capacity];
else
break;
ptr++;
}
if (q.length == 0) {
q.shift();
q.push(t[i]);
}
else {
let j = 0;
while (j < (ptr % capacity)) {
let t1 = q[0];
q.shift();
q.push(t1);
let temp = bitref[0];
for (let counter = 0; counter < capacity - 1; counter++)
bitref[counter] = bitref[counter + 1];
bitref[capacity - 1] = temp;
j++;
}
q.shift();
q.push(t[i]);
}
}
faults++;
}
else {
let temp = q;
let counter = 0;
while (q.length > 0) {
if (q[0] == t[i])
bitref[counter] = true;
counter++;
q.shift();
}
q = temp;
hits++;
}
}
console.log("Hits: " + (hits + 6));
console.log("Faults: " + (faults - 6));
}
let t = [2, 3, 2, 1, 5, 2, 4, 5, 3, 2, 5, 2];
let capacity = 4;
LRU_Approximation(t, capacity);
|
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
class HelloWorld {
public static bool findQueue(Queue<int> q, int x) {
foreach(Object i in q)
{
if(x == (int)i)
return true;
}
return false;
}
public static void LRU_Approximation(List<int> t, int capacity) {
int n = t.Count;
Queue<int> q = new Queue<int>();
int hits = 0, faults = 0;
bool[] bitref = new bool[capacity];
int ptr = 0;
int count = 0;
for (int i = 0; i < t.Count; i++) {
if (findQueue(q, t[i]) == false) {
if (count < capacity) {
q.Enqueue(t[i]);
count++;
}
else {
ptr = 0;
while (q.Count > 0) {
if (bitref[ptr % capacity])
bitref[ptr % capacity] = !bitref[ptr % capacity];
else
break;
ptr++;
}
if (q.Count == 0) {
q.Dequeue();
q.Enqueue(t[i]);
}
else {
int j = 0;
while (j < (ptr % capacity)) {
int t1 = q.Dequeue();
q.Enqueue(t1);
bool temp = bitref[0];
for (int counter = 0; counter < capacity - 1; counter++)
bitref[counter] = bitref[counter + 1];
bitref[capacity - 1] = temp;
j++;
}
q.Dequeue();
q.Enqueue(t[i]);
}
}
faults++;
}
else {
Queue<int> temp = new Queue<int>(q);
int counter = 0;
while (q.Count > 0){
if (q.Peek() == t[i])
bitref[counter] = true;
counter++;
q.Dequeue();
}
q = temp;
hits++;
}
}
Console.WriteLine("Hits: " + hits + "\nFaults: " + faults);
}
static void Main() {
var t = new List<int>(){2, 3, 2, 1, 5, 2, 4, 5, 3, 2, 5, 2};
int capacity = 4;
LRU_Approximation(t, capacity);
}
}
|
Advantages LRU Approximation (Second Chance Algorithm) are:
- The LRU approximation algorithm is easy to implement and requires very little overhead compared to other page replacement policies like the Optimal algorithm.
- It has a high hit rate in practice and performs well on most workloads.
- It can handle varying memory requirements and page access patterns.
Disadvantages LRU Approximation (Second Chance Algorithm) are:
- The LRU approximation algorithm may not always select the optimal page to evict, especially when there are frequent page references to a small set of pages.
- It can suffer from the “Belady’s Anomaly” where increasing the number of page frames can lead to more page faults.
- The Second Chance Algorithm may not be efficient in handling working sets that have a high turnover rate.
Unlock the Power of Placement Preparation!
Feeling lost in OS, DBMS, CN, SQL, and DSA chaos? Our Complete Interview Preparation Course is the ultimate guide to conquer placements. Trusted by over 100,000+ geeks, this course is your roadmap to interview triumph.
Ready to dive in? Explore our Free Demo Content and join our Complete Interview Preparation course.
Last Updated :
17 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...