0
0
Operating-systemsConceptBeginner · 3 min read

What is LRU Page Replacement: Explanation and Example

The LRU (Least Recently Used) page replacement algorithm removes the page that has not been used for the longest time when memory is full. It assumes pages used recently will likely be used again soon, so it replaces the oldest unused page to optimize memory use.
⚙️

How It Works

Imagine you have a small desk where you keep important papers (pages). When the desk is full and you need to add a new paper, you remove the one you haven't looked at for the longest time. This is the idea behind LRU page replacement.

In computer memory, when all page slots are full and a new page is needed, the system checks which page was used least recently and replaces it. This helps keep the most useful pages in memory, improving performance.

💻

Example

This example shows a simple simulation of the LRU page replacement algorithm in Python. It tracks pages in memory and replaces the least recently used page when needed.

python
def lru_page_replacement(pages, capacity):
    memory = []
    page_faults = 0

    for page in pages:
        if page in memory:
            memory.remove(page)  # Page used recently, move it to the end
        else:
            page_faults += 1
            if len(memory) == capacity:
                memory.pop(0)  # Remove least recently used page
        memory.append(page)
        print(f"Memory state: {memory}")

    return page_faults

pages = [7, 0, 1, 2, 0, 3, 0, 4, 2]
capacity = 3
faults = lru_page_replacement(pages, capacity)
print(f"Total page faults: {faults}")
Output
Memory state: [7] Memory state: [7, 0] Memory state: [7, 0, 1] Memory state: [0, 1, 2] Memory state: [1, 2, 0] Memory state: [2, 0, 3] Memory state: [0, 3] Memory state: [3, 0, 4] Memory state: [0, 4, 2] Total page faults: 6
🎯

When to Use

LRU is useful when you want to keep the most recently used data in memory because it predicts that recently used pages will be used again soon. It is commonly used in operating systems for managing memory and in caching systems like web browsers or databases.

Use LRU when you have limited memory and want to reduce slow disk accesses by keeping frequently accessed pages in fast memory.

Key Points

  • LRU replaces the page that was used longest ago.
  • It helps keep frequently used pages in memory.
  • It requires tracking page usage order.
  • Common in OS memory management and caching.

Key Takeaways

LRU removes the least recently used page to free memory.
It assumes recent pages are more likely to be used again soon.
LRU improves performance by keeping active pages in memory.
It is widely used in operating systems and caching systems.
Tracking usage order is essential for LRU to work correctly.