script to free up cached memory

on some of the app boxes at work we have an issue with tomcat not free’ing up cached memory quickly after either a tomcat restart or tomcat stop so we did some google-ing to find a way to quickly free up cached memory.

what this script does is sync writes the cache then echo 3 > /proc/sys/vm/drop_caches frees pagecache and inode/dentry caches.

here is the result :

#!/bin/bash

BC=`which bc`

if [ -z $BC ]; then
    printf "\nbc not found.\n"
    exit 1
fi

fm_pre=`echo \`cat /proc/meminfo | grep MemFree | tr -s ' ' | cut -d ' ' -f2\`/1024.0 | $BC`
cm_pre=`echo \`cat /proc/meminfo | grep "^Cached" | tr -s ' ' | cut -d ' ' -f2\`/1024.0 | $BC`
m_tot=`echo \`cat /proc/meminfo | grep MemTotal | tr -s ' ' | cut -d ' ' -f2\`/1024.0 | $BC`

printf "This script clears cached mem and free's up some ram.\n"
printf "cached memory : ${cm_pre}mb\n"
printf "free memory   : ${fm_pre}mb\n"
printf "total memory  : ${m_tot}mb\n"

sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"

fm_post=`echo \`cat /proc/meminfo | grep MemFree | tr -s ' ' | cut -d ' ' -f2\`/1024.0 | $BC`

printf "\nmemory freed  : `echo "${fm_post} - ${fm_pre}" | $BC`mb\n"
printf "total free    : ${fm_post}mb\n"

this script is run on several boxes all with kernels of 2.6.22 and higher and it also assumes that you have GNU bc installed (on gentoo: sys-devel/bc).

output of the script should look similar to :

> ./freemem.sh
This script clears cached mem and free's up some ram.
cached memory : 154mb
free memory   : 2672mb
total memory  : 3956mb
Password:

memory freed : 57mb
total free   : 2729mb

in the output, the password is required since i have the sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches" line which i did not give password-less sudo access.

«
»

    Leave a Reply

    Your email address will not be published. Required fields are marked *