What is Demand Paging: Explanation, Example, and Use Cases
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.
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))
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.