Today I would like to give a quick overview of how to use Visual VM to diagnose memory leaks in a Spring Boot application. Being able to debug memory leaks is a critical skill to have when developing enterprise-level applications. These types of issues could take days or weeks to cause serious errors, but when they do you will be happy knowing how to isolate the problem!
Firstly, go over to the Visual VM website and download the application zip. It is a standalone application so you do not need to install it. Unzip the files someplace convenient. Next, I am going to assume that you can run your Spring Boot application from the command line using a command such as
Once you are able to run your application from a terminal we need to pass some JVM arguments to allow Visual VM to profile your application and detect memory leaks:
-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.rmi.port=9010 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=localhost
The passing these arguments to Spring Boot will look like this:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Xdebug -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.rmi.port=9010 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=localhost"
NOTE: you can replace
localhost with the IP address of a remote server if you are not profiling a server locally.
Running Visual VM
Finally, navigate to the unzipped application folder and execute the
visualvm file which is located in the binary folder (
bin). Make sure your Spring Boot Application is running and click the “Add JMX Connection” in Visual VM. Next set the connection to
localhost:9010 (or whichever host you used) and click ok. There should now be a colored icon on the left-hand side which indicates you are connected to your app! If it is greyed out that means there is an issue with connecting Visual VM to your application. Double click the connection and you can now investigate memory leaks!
I will come back to update this will some real-life examples of how to find and FIX memory leaks! Happy debugging!