17.4.1 Automatic Restart

There are various ways to achieve reloading of classes on the JVM, all have their advantages and disadvantages. The following are possible ways to achieve reloading without restarting the JVM:

  • JVM Agents - A JVM agent like JRebel can be used, however these can produce unusual errors, may not support all JDK versions and can result in cached / stale classes.

  • ClassLoader Reloading - Class Loader based reloading is a popular solution used by most JVM frameworks, however it once again can lead to cached / stale classes, memory leaks and weird errors if the incorrect classloader is used at any moment.

  • Debugger HotSwap - The Java debugger supports hotswapping of changes at runtime, but only supports a few use cases.

Given the problems with existing solutions and a lack of a way built into the JVM to reload changes, the safest and best solution to reloading, and the one recommended by the Micronaut team, is to use automatic application restart via third-party tool.

Micronaut’s startup time is fast and automatic restart leads to a clean slate without potential hard to debug problems cropping up or memory leaks.

Maven Restart

To have automatic application restarts with Maven use the Micronaut Maven plugin (including by default when creating new Maven projects) and run the following command:

Using the Micronaut Maven Plugin

  1. $ ./mvnw mn:run

Every time you change a class Micronaut’s plugin will automatically restart the server.

Gradle Restart

Gradle automatic restart can be activated when using the Micronaut Gradle plugin simply by activating Gradle’s support for continuous builds via the -t flag:

Using Gradle for Automatic Restart

  1. ./gradlew run -t

Every time you make a change to class or resources Gradle will recompile and restart the application.