0
0
Operating-systemsConceptBeginner · 3 min read

What is Demand Paging: Explanation, Example, and Use Cases

Demand paging is a memory management technique where pages of data are loaded into memory only when they are needed, rather than all at once. This helps save memory and speeds up program startup by loading pages on demand.
⚙️

How It Works

Demand paging works like a library that only brings you the book pages you want to read instead of the whole book at once. When a program runs, it doesn't load all its data into memory immediately. Instead, it waits until a specific part of the program needs a page of memory.

When the program tries to access a page that is not in memory, the operating system pauses the program and loads that page from the disk into memory. This process is called a page fault. After loading, the program continues as if the page was always there.

This method saves memory and reduces the time it takes to start programs because only the necessary pages are loaded.

💻

Example

This simple Python example simulates demand paging by loading data only when requested.

python
class DemandPagingSimulator:
    def __init__(self):
        self.pages = {}

    def access_page(self, page_number):
        if page_number not in self.pages:
            print(f"Page {page_number} not in memory. Loading page...")
            self.pages[page_number] = f"Data of page {page_number}"
        else:
            print(f"Page {page_number} already in memory.")
        return self.pages[page_number]

simulator = DemandPagingSimulator()
print(simulator.access_page(1))
print(simulator.access_page(2))
print(simulator.access_page(1))
Output
Page 1 not in memory. Loading page... Data of page 1 Page 2 not in memory. Loading page... Data of page 2 Page 1 already in memory. Data of page 1
🎯

When to Use

Demand paging is useful in operating systems to efficiently manage memory when running multiple programs. It helps avoid loading unnecessary data, which saves memory and improves system performance.

Real-world use cases include:

  • Running large applications where loading all data at once would be slow or wasteful.
  • Systems with limited memory resources, like mobile devices.
  • Virtual memory systems that allow programs to use more memory than physically available.

Key Points

  • Demand paging loads pages only when needed, not all at once.
  • It reduces memory usage and speeds up program start.
  • A page fault triggers loading a missing page from disk.
  • Common in modern operating systems with virtual memory.

Key Takeaways

Demand paging loads memory pages only when the program accesses them.
It improves memory efficiency and program startup speed.
Page faults occur when a needed page is not in memory and must be loaded.
This technique is essential for virtual memory management in modern OS.
Demand paging helps systems run large programs with limited physical memory.