← Guides

Gradle daemon memory on a Mac

By , who makes Ramback · Updated

After a build, Gradle leaves a daemon JVM running so the next build starts fast. It stays up for 3 idle hours, Kotlin projects leave a Kotlin compile daemon next to it, and a JVM rarely hands memory back once its heap has grown. Each daemon holds 1–2 GB, so two or three projects can mean several gigabytes doing nothing. To stop all of them, whatever their Gradle version, run pkill -f GradleDaemon.

See every Gradle and Kotlin daemon

From a project folder, ./gradlew --status lists the daemons, but only those running that project's Gradle version. To see all of them with their memory:

ps -axo pid=,rss=,command= | awk '/[G]radleDaemon|[K]otlinCompileDaemon/ {printf "%6s %6.0f MB  %s\n", $1, $2/1024, (/Kotlin/ ? "Kotlin daemon" : "Gradle daemon")}'

Why are several Gradle daemons running?

Gradle reuses a daemon only when the Gradle version, the JDK and the JVM arguments all match. Change any of them and the next build starts a new daemon, while the old one waits out its 3 hours. The usual causes:

The Kotlin daemon starts with the first Kotlin compile and uses the same JDK as the Gradle daemon. A second one starts only when no running Kotlin daemon has matching JVM arguments or a big enough heap. It exits with the Gradle daemon, or after 2 hours without compiling. To have one JVM instead of two, kotlin.compiler.execution.strategy=in-process compiles Kotlin inside the Gradle daemon. Kotlin's docs call the separate daemon the faster option.

Stop the Gradle daemons

# daemons of this project's Gradle version
./gradlew --stop

# every Gradle and Kotlin daemon, any version
pkill -f GradleDaemon
pkill -f KotlinCompileDaemon

--stop leaves daemons from other Gradle versions alone, which is why memory often doesn't drop as much as you expect. pkill sends SIGTERM, so the daemons shut down cleanly. Don't run either in the middle of a build: it fails, and the next build starts a fresh daemon.

For a one-off build, ./gradlew build --no-daemon doesn't leave a daemon behind.

Make the daemons smaller

Put these in ~/.gradle/gradle.properties to cover every project. Values there override each project's own gradle.properties.

# Gradle daemon heap. Gradle's own default is 512 MB; Android project templates set 2 GB.
org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8

# Exit after 1 idle hour. The value is in milliseconds; the default, 10800000, is 3 hours.
org.gradle.daemon.idletimeout=3600000

# Kotlin daemon heap. Without this it copies -Xmx from the Gradle daemon.
kotlin.daemon.jvmargs=-Xmx1g

Too small a heap makes builds slow or fail with OutOfMemoryError. 2 GB for Gradle and 1 GB for Kotlin suit most mid-size Android apps; raise them if builds start failing.