How to Clear Swap Space, Memory Cache and Buffer on Linux

How to Clear Swap Space, Memory Cache and Buffer on Linux

 

The linux Kernels have a mechanism to drop the page cache and/or inode and dentry caches on command, which can avail free up an abundance of system memory. Now you can discard that script that allocated a ton of memory just to waive of the cache.

Clearing SWAP Memory

To clear the swap memory on your system, you simply need to cycle off the swap. This moves all data from swap memory back to RAM. It additionally betokens that you require to be sure you have the RAM to assist this operation. A facile way to do this is to run 'free -m' to check what is being utilized in swap and in RAM.
The following command will help you to clear the SWAP memory.

swapoff -a
#(use free -m to see the amount of swap used/available decrease over time)
swapon -a 

What is Memory Cache.

In order to speed operations and abbreviate disk I/O, the kernel conventionally does as much caching, pages containing cached data can be repurposed on-demand for other uses (e.g., apps) Repurposing recollection for use in this way is no more gradual than claiming pristine untouched pages.
echo the number to /proc/sys/vm/drop_caches to clear the cache.
Example: #echo 1 > /proc/sys/vm/drop_caches

To free pagecache:

 sync; echo 1 > /proc/sys/vm/drop_caches

To Clear dentries and inodes.:

 sync; echo 2 > /proc/sys/vm/drop_caches 

In order to clear PageCache, dentries and inodes run:

 sync; echo 3 > /proc/sys/vm/drop_caches 

Page cache is memory held after reading files. Linux kernel prefers to keep unused page cache assuming files being read once will most likely to be read again in the near future, hence avoiding the performance impact on disk IO.
An Inode is a data structure which provides a representation of a file. Dentries is a data structure which represents a directory or a folder. So, dentries can be used to store cache, if they exist then store or check from memory.

The sync command forces an immediate write of all cached data to disk. Run sync if you anticipate the system to be unstable, or the storage device to become suddenly unavailable, and you want to ensure all data is written to disk. Individual files may be synced, or the entire filesystem containing the specified files.
Using sync; is optional in the above examples.

Caution: Using vm.drop_caches can cause a deadlock if the system is under heavy I/O and Memory load.


Technology Python Programming Entertainment Python3 Linux Web-development Linux-mint Centos 7 Book
ziabs @ 05 Jul 2020