# Page Replacement Logics (Animated): Belady’s Anomaly in FIFO vs LRU & Optimal Stack Property
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Operating Systems
Canonical URL: https://gateandnet.com/exams/gate-cs/operating-systems/animated-page-replacement-belady-fifo-lru-optimal

> Interactive frame-by-frame proof of Belady’s Anomaly (9 faults with 3 frames vs 10 faults with 4 frames under FIFO!), Mattson’s Stack Inclusion Property, Second-Chance Clock, and Working-Set Thrashing.

## 1. Interactive Belady’s Anomaly Animator (Switch FIFO 3 Frames vs 4 Frames!)

Run **FIFO with 3 Frames** ($9$ page faults) and then click **4 Frames** ($10$ page faults!) on the classic reference string `1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5`, then switch to **LRU** ($10 \to 8$ faults) to see why stack algorithms never suffer from Belady’s Anomaly:

```visualizer
lru-fifo
```

## 2. Why LRU Needs Hardware Assistance & Clock (Second-Chance) Approximation

- **Exact LRU Implementation:** Requires either a **64-bit hardware timestamp counter** updated on *every memory reference* or a doubly-linked stack of frame numbers — too expensive for software interrupts on hits!
- **Clock (Second-Chance) Algorithm:** Arranges frames in a circular buffer with a **1-bit hardware Reference Bit $R$**:
  - If $R = 0$: evict immediately!
  - If $R = 1$: clear $R \leftarrow 0$ (give a *second chance*) and advance the clock hand. *(If all frames have $R = 1$, Clock degenerates to pure **FIFO**!)*
- **Thrashing & Working-Set Model $\Delta$:** Occurs when $\sum_i \text{WSS}_i > D$ (sum of active locality working sets exceeds total RAM frames), causing CPU utilization to **plummet** as the OS scheduler mistakenly adds even *more* degree of multiprogramming!

## Solved Practice Questions & PYQs

### [GATE CS 2022 | NAT]
Consider a system with **$3$ initially empty page frames** and page reference string `1, 2, 3, 4, 2, 1, 5, 3, 2, 4, 6`. How many **page faults** occur under **Optimal (MIN)** page replacement?
**Correct Answer:** 7
**Solution:** 1. `1, 2, 3` $\to [1,2,3]$ ($3$ cold faults)
2. `4`: future uses of `1`(pos 5), `2`(pos 4), `3`(pos 7) $\to$ evict `3` $\implies [1,2,4]$ (fault #4)
3. `2`: Hit! `1`: Hit!
4. `5`: future uses `1`(never), `2`(pos 8), `4`(pos 9) $\to$ evict `1` $\implies [5,2,4]$ (fault #5)
5. `3`: future uses `5`(never), `2`(pos 8), `4`(pos 9) $\to$ evict `5` $\implies [3,2,4]$ (fault #6)
6. `2`: Hit! `4`: Hit!
7. `6`: evict any $\to$ (fault #7).
Total Optimal page faults $= \mathbf{7}$.
