Clearing Inactive Memory in Linux
I use Nagios to monitor my systems and occasionally get alerts that I had high memory utilization on some of my machines. But using
free -m, all I found was confusion.
Until recently, I thought the only way to free up the memory was to reboot the server. When it comes to how OS's manage their memory, it can be kind of unclear for some people.
free -m often don't seem to line up is because of the different states of memory. There are two states of used memory, inactive and active.
Active memory is memory that is being used by a particular process. Inactive memory is memory that was allocated to a process that is no longer running.
free -m do not differentiate between these two types of memory. This is why
free -m may show only 2% memory available. while
top may only show a few processes using 1 or 2%.
To better understand the differences between inactive and active memory, think of it this way. If you were to write something on a dry-erase board starting from the top left, and then you no-longer needed the information, you probably wouldn't erase that sentence and start in the top left again. You would probably drop to the next line and write in the next available space and only erase the information when you run out of available surface area.
The same concept holds true for memory in a computer. Instead of cleaning the dirty memory, the computer just lets it sit there. It's not causing any detrimental effects or costing the computer anything in terms of performance or usability. The computer simply waits until the memory is needed again before it clears it up and writes the new data to that section.
Over time this can cause the levels of inactive memory to climb and therefore the level of "used" memory, and eventually, trigger threshold alarms. Especially if you run memory intensive applications or scripts.
To determine whether or not you have a lot of inactive memory on a Linux system, look at
On about the 6th and 7th lines, you should see two fields sowing how much memory is active and how much is inactive.
... Active: 9010124 kB Inactive: 4607032 kB ...
If you have a large amount of inactive memory, there are two ways that you can clear it up to make the threshold alarm go away.
Reboot the system or
free && sync && echo 3 > /proc/sys/vm/drop_caches && echo "" && free
This command shows you the current state of the memory according to
free and then clears the memory buffers/cache and then shows the new details as reported by
free. Keep in mind though that if you still have high levels of usage after running this command, it is probably actually being used by a process and as such can not be cleared without killing the process or restarting the box.