Resolving PermGen space errors when building Android using gradlew

While fixing out of memory errors when building Android apps is usually easy, there is a less common issue you may run across, that of the build process running out of PermGen space.

Before I get into the details of the issue, and how to fix it, I have some good news: Permgen has been removed in Java 8; both Oracle Java 8 and OpenJDK 8.

The best news is you don’t have to wait for the download to upgrade, The CircleCi Trusty 14.04 build boxes come pre-installed with Java 8 so you can switch the project over and get building.

What if I can’t switch? How do I fix ‘out of memory errors’?

What is PermGen? This article does an excellent job of explaining it.

But, you might ask, why does setting the _JAVA_OPTIONS seem to do nothing in terms of controlling the memory usage of your Android builds? Well, it turns out that gradlew, the build wrapper that Android (and a lot of other projects) use, doesn’t honor the the Java options, as explained in our out of memory documentation

So how do we fix the PermGen space issues, if you switch your project to Java 8, and the Java options don’t work?

You edit you circle.yml file to look like this:

        GRADLE_OPTS: '-Dorg.gradle.jvmargs="-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError -XX:MaxPermSize=512m"'

You can change the memory usage as needed (please remember our build boxes default to a memory limit of 4G), but the important part here is the -XX:MaxPermSize=512m. You can start with 256m if you like, but I have run some massive Java applications and have never run into PermGen space issues with it set to 512m.

I hope this helps, and happy building on CircleCi!

1 Like