Labs ICT
Pro Login

Swapping

Moving processes between memory and disk to save space.

What is Swapping?

Imagine you have a small desk (RAM) but dozens of projects (processes) to work on. You can't fit all projects on the desk at once, so you keep only the active ones there and move the others to a filing cabinet (disk). When you need to work on a project from the cabinet, you bring it back to the desk and put away something less urgent.

This is exactly what swapping does. When memory gets tight, the OS moves (swaps) entire processes from RAM to a special area on disk called the swap space. When those processes need to run again, they're swapped back into memory.

How Swapping Works

The swapping process is straightforward:

  1. The OS detects that memory is running low — there aren't enough free frames to accommodate a new process or handle a page fault.
  2. It selects a process to swap out (usually one that's been idle or has low priority).
  3. The entire process — code, data, stack, heap — is written to the swap space on disk.
  4. The memory frames previously used by that process are freed and given to other processes.
  5. When the swapped-out process needs to run again, it's read back into memory, potentially at different physical addresses.

The Cost of Swapping

Swapping sounds like a great solution for limited memory, but there's a huge catch: disk access is thousands of times slower than RAM access. Reading from or writing to disk takes milliseconds, while RAM access takes nanoseconds. That's a million-fold difference.

If the OS swaps too aggressively, the system spends more time moving processes between memory and disk than actually running them. This thrashing-like behavior makes the computer feel sluggish and unresponsive.

The OS must be smart about what it swaps. It typically prefers swapping out processes that have been idle for a long time or have low priority, rather than actively running processes.

Context Switch Cost with Swapping

When a swapped-out process is brought back, a context switch becomes more expensive. The OS needs to:

  • Read the entire process from disk back into memory.
  • Update the page tables and memory mappings.
  • Restore the process's state from its PCB.

This can take several milliseconds — an eternity in CPU time. That's why modern operating systems prefer virtual memory (covered in a later lesson) over full-process swapping. Virtual memory allows more fine-grained control, moving individual pages rather than entire processes.