Limiting Android Studio Memory Use Using systemd-run ad-hoc CGroups

If you're developing Android apps using Android Studio, it's not uncommon for you to experience a sluggish overall system performance when Android Studio is doing its thing.

More specifically in my case, on my laptop with 24GB RAM, running a web browser along with Android Studio meant all kinds of weird behaviour – from frozen tabs to failed downloads and sluggish mouse movements – leading me to file frivolous bugs in browser forums. The root cause being Android Studio's memory consumption forcing my system to swap to my SSD and affecting disk performance.

One option is to set vm.swappiness kernel parameter to 0 from the current sysctl vm.swappiness = 60. This would also help extend the life of my SSD. But in general, I've never seen the swapfile being used on my system even with 50+ browser tabs open and VS Code running merrily. See here if this is an option for you.

Instead, I prefer limiting resources to the problematic memory-hungry apps.

Here's what works on my Linux Mint system using kernel CGroups:

systemd-run \
  --user \
  -p MemoryLimit=10G \
  -p CPUShares=100 \
  --unit=android-studio \
  --slice=android-studio \
  $PATH_TO/android-studio/bin/studio.sh
`systemctl --user status android-studio` shows memory use is limited to 10G

A transient systemd unit file is automatically created with the following configuration:

# This is a transient unit file, created programmatically via the systemd API. Do not edit.
[Unit]
Description=/home/shirish/apps/android-studio/bin/studio.sh

[Service]
MemoryLimit=10737418240
CPUShares=100
Slice=android-studio.slice
ExecStart="/home/shirish/apps/android-studio/bin/studio.sh"
systemctl --user cat android-studio
[Desktop Entry]
Version=1.0
Type=Application
Name=Android Studio
Icon=$PATH_TO/android-studio/bin/studio.svg
Exec=systemd-run -p MemoryLimit=10G -p CPUShares=100 --unit=android-studio --slice=android-studio --user "$PATH_TO/android-studio/bin/studio.sh" %f
Comment=The Drive to Develop
Categories=Development;IDE;
Terminal=false
StartupWMClass=jetbrains-studio
StartupNotify=true
Update $HOME/.local/share/applications/jetbrains-studio.desktop

Background

Limiting Android Studio's memory consumption through configuration is no easy task. Ideally, you'd want a single setting to govern the whole suite of internal tasks Android Studio runs to compile, assemble, deploy, emulate your app. But there's no escaping the myriad set of technologies at play – the JVM, Gradle daemon, Kotlin daemon, Emulator, the IDE itself and optionally IDE plugins like Github Copilot (if you're using it).

Although Android Studio makes an effort in helping you configure some of these memory settings, there's no holistic estimate of how much memory you're going to end up using for Android development.