why is some of my swap space being used, when I still have unused RAM?

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.


Solution 1:

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.

Solution 2:

It makes sense to swap out things in advance since when you really need the memory, you won't have to wait until the kernel is done with disk access.

For example, let's say you want to open a large image. When the image is loaded, it takes 300MB of RAM. If the kernel uses all the RAM it can, loading your image requires that the kernel transfers 200MB from the RAM to the disk. If it proactively emptied the RAM beforehand, you save a few milliseconds.