void
void

Reputation: 761

Spring boot notificatoin/restart upon critical error

I have a Spring Boot app, that runs on a ec2 server. I do not expect any critical error, however, I would like to secure the app from a total halt. For example, if OutOfMemory is thrown, JVM stops and I'm not aware of it.

Is there a way to configure the app/server in such a way, that if any critical error occurs it is automatically restarted? Thanks in advance.

Upvotes: 0

Views: 2527

Answers (2)

Magnus
Magnus

Reputation: 8308

You could do something like:

public static void main(String... args) throws Exception {
    while(true){
        try(ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args)) {
            CompletableFuture<Throwable> throwableFuture = new CompletableFuture<>();
            Thread.setDefaultUncaughtExceptionHandler(
                    (thread, throwable) -> throwableFuture.completeExceptionally(throwable));
            throwableFuture.get();
        } catch (Exception | VirtualMachineError t) {
            //log error
        }
    }
}

This will wait for any threads to throw an uncaught exception.
The try-with-resources statement will close the context and cleanup any resources associated with it.
The while loop will then recreate the context.

You will need to make sure that any resources you create(like thread factories) and being properly disposed of when the context closes, otherwise you will still run out of memory.

A better approach would be to have your java service restarted by an external service manager like systemd.

Upvotes: 1

Darshan Mehta
Darshan Mehta

Reputation: 30849

You can add a couple of dependencies to your application:

  • Spring-boot-starter-actuator: This exposes a lot of endpoints to check the App status, logs, get thread dumps etc.
  • spring-cloud-context: This contains RestartEndpoint which you can autowire into your application, and expose an API endpoint to restart the application.

Once done, you can use any HTTP monitoring tool (like Spring Admin) to monitor the apps and restart if/when needed.

Upvotes: 2

Related Questions