Tuesday, November 17, 2015

2. Why is swap being used even though I have plenty of free RAM?

2. Why is swap being used even though I have plenty of free RAM?


Setting the swappiness value doesn't work in every situation. If it works for you, great. If not, I've written a script to periodically clear out swap by turning it off and back on again.
Toggling swap is a bit risky if you're not careful. If you don't have enough free RAM to hold everything in RAM plus everything in swap, trying to disable swap will cause your system to become unresponsive. My script first checks whether there's enough free RAM (which takes a bit of doing, as the actual amount of free RAM is different from what free reports as free), then only toggles swap if so. But, if you're a bit short on RAM, don't start another major process while the script is running. Here it is:
#!/bin/bash

# Make sure that all text is parsed in the same language
export LC_MESSAGES=en_US.UTF-8
export LC_COLLATE=en_US.UTF-8
export LANG=en_US.utf8
export LANGUAGE=en_US:en
export LC_CTYPE=en_US.UTF-8

# Calculate how much memory and swap is free
free_data="$(free)"
mem_data="$(echo "$free_data" | grep 'Mem:')"
free_mem="$(echo "$mem_data" | awk '{print $4}')"
buffers="$(echo "$mem_data" | awk '{print $6}')"
cache="$(echo "$mem_data" | awk '{print $7}')"
total_free=$((free_mem + buffers + cache))
used_swap="$(echo "$free_data" | grep 'Swap:' | awk '{print $3}')"

echo -e "Free memory:\t$total_free kB ($((total_free / 1024)) MB)\nUsed swap:\t$used_swap kB ($((used_swap / 1024)) MB)"

# Do the work
if [[ $used_swap -eq 0 ]]; then
    echo "Congratulations! No swap is in use."
elif [[ $used_swap -lt $total_free ]]; then
    echo "Freeing swap..."
    swapoff -a
    swapon -a
else
    echo "Not enough free memory. Exiting."
    exit 1
fi
You must run this script as root (e.g., with sudo). This script won't leave your system unresponsive; if you've got insufficient RAM, it will refuse to toggle swap. I've used this script without problems for close to five years now.

No comments:

Post a Comment

  How to Change Instance Type & Security Group of EC2 in AWS By David Taylor Updated April 29, 2023 EC2 stands for Elastic Compute Cloud...