Shutdown and exit codes

A server or a scheduler runs until it is stopped. To stop cleanly, the context must close when the process gets SIGINT (Ctrl+C) or SIGTERM (kill, a container stop): then the web server finishes its running requests, @PreDestroy methods and ContextClosedEvent listeners run, and the process ends. A command-line tool, on the other hand, ends by itself and often has to tell its caller how it went, with an exit code.

Why

A process killed in the middle of its work leaves connections open, files half written and requests unanswered. Closing the context on a signal gives every bean a chance to finish. An exit code lets a shell script or a CI job react to a batch that partly failed.

Example

A server that stops gracefully:

# lib/resources/application.properties
spring.main.register-shutdown-hook=true
spring.lifecycle.timeout-per-shutdown-phase=20s
server.shutdown=graceful
@Component()
@Log()
class Outbox {
  // Runs when the context closes, also on Ctrl+C with the hook on.
  @PreDestroy()
  Future<void> flush() async {
    log.info('Sending the last messages');
    await _send();
  }
}

A tool that tells the shell whether some items failed:

@Component()
class FailedJobs implements ExitCodeGenerator {
  int failed = 0;

  @override
  int getExitCode() => failed > 0 ? 2 : 0;
}

Future<void> main(List<String> args) async {
  final context = await runApplicationAsync(args);   // runs the job's runners
  exit(SpringApplication.exit(context));              // dart:io; 0 or 2
}

The shutdown hook

Setting Default Meaning
spring.main.register-shutdown-hook false Closes the context on SIGINT or SIGTERM. Wins over the constructor
SpringApplication(registerShutdownHook: true) false The same, in code

With the hook on, on SIGINT the context is closed and the process ends with exit(130); on SIGTERM with exit(143). It uses the context's registerShutdownHook(). The listener goes away when the context closes by other means.

It is off by default, unlike in Spring Boot. A Dart program that listens for signals does not end by itself, so a tool that has finished its work would never exit. Turn it on in programs that run until stopped: servers, schedulers, workers. It listens through dart:io, so it does nothing on the web, and Flutter apps close their context through the app lifecycle instead.

The shutdown timeout

When the context closes, the lifecycleProcessor stops the lifecycle beans phase by phase, the web server among them, and waits at most spring.lifecycle.timeout-per-shutdown-phase for each phase. Then it goes on and the beans are destroyed.

Key Type Default Meaning
spring.lifecycle.timeout-per-shutdown-phase Duration 30s How long one shutdown phase may take, for example the web server's graceful shutdown

The processor comes from LifecycleAutoConfiguration. Without it (excluded, or a context created by hand) the context waits 10 s, Spring Framework's default, whatever the property says.

Exit codes

SpringApplication.exit(context, [generators]) closes the context and returns the code the process should exit with:

  1. It asks the generators passed as the second argument and the ExitCodeGenerator beans, sorted by order (Ordered, @Order).
  2. The first non-zero code wins; 0 when there is none.
  3. A non-zero code is published as an ExitCodeEvent before the context closes.
  4. A failure on the way, closing included, is logged as a warning and gives 1, unless a code was found already.

Pass the result to exit from dart:io.

Exit codes of a failed run

When a runner fails, the code comes from the ExitCodeExceptionMapper beans (asked while the context is still active), else from the exception itself when it implements ExitCodeGenerator. The code is published as an ExitCodeEvent, and SpringApplication.exitCodeOf(error) returns it:

// Map the importer's errors to codes the operators know.
@Component()
class ImportErrors implements ExitCodeExceptionMapper {
  @override
  int getExitCode(Object exception) => switch (exception) {
        FileSystemException() => 3,
        FormatException() => 4,
        _ => 0,
      };
}

Future<void> main(List<String> args) async {
  try {
    await runApplicationAsync(args);
  } catch (error) {
    exit(SpringApplication.exitCodeOf(error) ?? 1);
  }
}

A start that fails while creating the beans has no code from the mappers (the context is not active), and strings or numbers thrown as errors never have one.

In Spring (Java)

System.exit(SpringApplication.exit(SpringApplication.run(Job.class, args)));

Differences:

See also