Linux – Does page swapping happen when the main memory is still available

kernellinuxswapvirtual-memory

I just stumbled upon a random question that goes like, does the Linux kernel swap out any memory pages even when there are still some available memory spaces? I thought it does not in principle, but the Linux distributions still usually demand a dedicated swap partition when it's installed.

To put this in another way, can I unset the entire swap partition and still get the stable Linux system, given that I have a sufficient amount of main memory that I cannot exhaustively use?

Best Answer

does the Linux kernel swap out any memory pages even when there are still some available memory spaces

Check out vim /proc/sys/vm/swapiness (on Ubuntu at least). This specifies how often swaps are done and can imply that swaps are done even when memory is available. The real reasoning to find an optimal value for this heavily depends on the way the OS works, the available memory, and the processor itself. (My swapiness is specified at 60.)

From what I see in newer updates is that Linux automatically creates a /swapfile (which grows in size to 1-2 GBs) using available storage space, if no swap partition is specified. This does not explicitly exhaust your secondary storage but just makes your computer run smoother. Look at the output of ubuntu@ubuntu:/home/ubuntu$ swapon. Mine is:

NAME      TYPE      SIZE   USED PRIO  
/swapfile file      1.1G 123.5M   -2  
/dev/sda6 partition   2G   1.7G    1

This means you can pretty much "get the stable Linux system", without a swap partition.

The only exception is that a swap partition makes reloading semi-saved (or unsaved) information easier when your OS hibernate/crashes and you switch to another OS in between. (I am unsure but I think this is because the swap partition holds a /hiberfile.)

Related Question