1. Overview

The JVM’s default heap size might not be enough for processing large requests or files. In this tutorial, we’ll have a look at several ways to configure the JVM heap size for applications built with SBT.

Note that the presented solutions will work for SBT version 1.0.0 or higher.

2. OutOfMemoryError

Scala applications use the heap to store objects. If we process large files or we have many objects in memory, we most likely found ourselves facing the following error:

java.lang.OutOfMemoryError: Java heap space

This happens when we try to put too many objects in memory over the heap’s threshold. Both Java and Scala have the same underlying details regarding heap usage, as both use the JVM.

3. Configuring Heap Size for SBT

Configuring heap size for SBT is not very different from setting it in other build tools like Maven or Gradle. Since the JVM allows us to configure several parameters, we need to specify the one that corresponds to the heap size. To do this, we specify the JVM -Xmx option, which sets the maximum heap size. As an example, let’s set the heap size to 2Gb of RAM:

$ export SBT_OPTS="-XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=2G -Xmx2G -Xms1G"

In this way, we can adjust this value to our needs. We have also specified the –Xms option which tells the JVM what’s the initial memory allocation for our application.

Alternatively, SBT allows us to specify the JVM options on a file named .jvmopts. Let’s set this option in the root of the project:

$ cat .jvmopts

4. Conclusion

In this tutorial, we saw how to configure the heap size on an application managed by SBT with two different approaches.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.