Linux – why is some of the swap space being used, when I still have unused RAM

linuxmemory

More of a curiosity than a problem; and, I admit, something of an embarassingly basic question:

I've noticed that on many occasions, on my Linux machine I will have ~500MB of swap space in use, even though I have ~600MB of unused RAM.

My naive high-level understanding was, swap space doesn't kick in until RAM is exhausted.

I went further and made the assumption that this situation must be the doing of the Linux kernel, because a user process that requests memory, does so only logically, and has no notion of whether that memory is physically backed by RAM or the swap space.

Which leads to the question, why would the kernel preemptively use the swap space? Is this part of some performance tuning algorithm? Is it swapping out to disk parts of memory that it deems least likely to be accessed (an LRU scheme, perhaps)? If so, wouldn't it just make sense to leave everything in RAM, and only when nearing exhaustion, then and only then swap the LRU portions from RAM to the swap space?

I should clarify, my linux server has 2GB of RAM and 2GB of swap space.

Best Answer

The unused part of the RAM is in fact used as HDD cache. If you think about it, you actually read parts of your disk more often that you access some parts of the RAM. Which makes sense to put this RAM on the disk, while using RAM to cache HDD data.

Related Question