Swap is memory acquired by an operating system from the secondary storage device to perform operational tasks. This happens when the primary memory (RAM) is full and needs extra storage to run the normal functionality.
Swap memory is an efficient method to manage the memory needs of the system. However, it also comes with some disadvantages. For example, it is often slower than the primary memory, which overall slows down the system’s performance. In the case of a memory glitch (OOM), it can also cause the server to crash.
In normal operations, the system efficiently manages the swap; however, in certain cases, it becomes essential to manage it manually by an administrator. In this guide, I will go through a process of clearing swaps on Linux and how to manage it.
How to Clear Swap on Linux
Clearing swap on Linux is as simple as turning a process off and on. To check the current status of swap using the free command with the -m flag.
Where -m displays the output in MBs, and to get output in GBs use the -g flag.
Disable the swap using swapoff command.
The -a flag indicates all devices marked as a swap in the /etc/swap directory. It stops using swap space and relies solely on RAM.
The swapoff process may take time to clear, therefore, hold on for a few seconds to let the process complete. To view the data transfer, use the free command.
Activate the swap using the swapon command.
The swap has been cleared; you can verify it using the free -m command.
How to Manage Swap on Linux
Swap on Linux is controlled using a Kernel parameter called swappiness. Like everything on Linux, swappiness is also a file located in the /proc/sys/vm directory. To read the file, use the cat command with the file path.
The output screenshot indicates the default value of swappiness 60. To modify the value of swappiness we need to access the sysctl.conf file.
Change the value of the vm.swappiness parameter with some other value. If this parameter does not exist, just type it.
Where N is the value of the swappiness.
The swap value can be set between 0 and 100; 0 will keep the swap disabled, while 100 indicates aggressive swapping.
After making the changes to the sysctl.conf file, you need to reboot the system to make the changes to take effect. Then check the value of swappiness using the cat command.
Conclusion
The swap is an efficient way of managing the memory in any operating system. Sometimes, aggressive swapping may occur due to abnormal application behavior, ultimately making the system slow and causing out-of-memory errors. Clearing the swap can rectify the situation. To clear the swap on Linux, reset it using the swapoff and then swapon commands. To manage the swap value, modify the vm.swappiness parameter in the sysctl.conf file.