Should you use swap with Java?
Swap is disk used as slow memory. If the JVM heap itself ends up on swap, garbage collection has to touch pages on disk and the application stalls for seconds. So the rule is: size the heap so that the JVM fits in RAM, and keep a small swap only as a buffer. It lets the kernel move idle pages (old daemons, unused parts of the OS) out of the way and gives you time to react instead of an instant OOM kill.
Many VPS images come without any swap. Check: swapon --show and free -m.
Create a swap file
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
swapon --show
If fallocate fails on your filesystem, use sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 instead.
Make the kernel prefer RAM
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
sudo sysctl --system
cat /proc/sys/vm/swappiness
The default of 60 swaps too eagerly for a server running a JVM and a database.
How much
- 2 GB RAM: 1 to 2 GB swap.
- 4 to 8 GB RAM: 1 to 2 GB swap.
- 16 GB and more: 2 GB is plenty, or none at all.
Watch it
vmstat 5 # columns si and so: they should stay near 0
free -m
If swap use keeps growing, or si and so are constantly above zero, the server is too small or the heap is too large. The fix is a lower -Xmx, less work on the server or a bigger plan. Compare sizes on the price page.
Last updated October 29, 2026.