springboot-Ways to do JVM optimizations for springboot apps

1. The purpose of this post

This post would demo how to do JVM optimizations for springboot apps.

2. Environments

  • java 1.8+

3. How to do it

3.1 the VisualVM tool

Make sure that you have the VisualVM tool, this tool can visualize the JVM heap and threads for you.

Just do as follows:

cd $JAVA_HOME // for windows users, type cd %JAVA_HOME%
./jvisualvm

Then you should get this screen: jVisualVM

We would use this tool to check if our JVM options is active.

3.2 The JVM options to set

From jdk 1.8 on, there are a few JVM options to optimize for springboot apps:

  • -XX:MetaspaceSize=128m (default size of metaspace)
  • -XX:MaxMetaspaceSize=128m (max size of metaspace)
  • -Xms1024m (default size of heap memory)
  • -Xmx1024m (max size of heap memory)
  • -Xmn256m (size of new generations memory)
  • -Xss256k (size of stack memory)
  • -XX:SurvivorRatio=8 (the survivor ratio 8:2)
  • -XX:+UseConcMarkSweepGC (Specify the GC implementation)
  • -XX:+PrintGCDetails (print the GC logs)

From JDK 1.8 on, There is no -XX:PermSize and -XX:MaxPermGen, they are replaced by

  • -XX:MetaspaceSize=128m
  • -XX:MaxMetaspaceSize=128m

Metaspace is only limited by the heap memory space, but it’s not good to make it so big, we should use the XX:MaxMetaspaceSize to limit the size of the MetaSpace.

3.3 Set the JVM options in IntelliJ Idea

In intelliJ Idea, you can set the above JVM options for springboot apps in the run configurations like this:

jVisualVM

3.4 Set the JVM options in command line

Before run in command line, we must package the springboot apps, we would package it using the springboot maven build plugin.

Add this plugin to your pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <classifier>exec</classifier>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
mvn package -Dmaven.test.skip=true

Then , there should be two jars in your target directory. The bigger is the jar that can be executed in command line.

How to add JVM options to it? Just do this:

 java -jar -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m -Xms1024m -Xmx1024m -Xmn256m -Xss256k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC springboot1-testapp-1.0-SNAPSHOT-exec.jar 

Open your VisualVM, and connect to this process, then you would get this: Command line options

Notice that, the max heap memory is about 1G bytes, our settings is active.

And then check the metaspace settings: Command line options2

You can see that the metaspace max size is about 128m, everything is ok.