Quarkus - Application Initialization and Termination

You often need to execute custom actions when the application starts and clean up everything when the application stops. This guide explains how to:

  • Write a Quarkus application with a main method

  • Write command mode applications that run a task and then terminate

  • Be notified when the application starts

  • Be notified when the application stops

Prerequisites

To complete this guide, you need:

  • less than 10 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.6.2+

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the lifecycle-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=lifecycle-quickstart \
  4. -DclassName="org.acme.lifecycle.GreetingResource" \
  5. -Dpath="/hello"
  6. cd lifecycle-quickstart

It generates:

  • the Maven structure

  • a landing page accessible on [http://localhost:8080](http://localhost:8080)

  • example Dockerfile files for both native and jvm modes

  • the application configuration file

  • an org.acme.lifecycle.GreetingResource resource

  • an associated test

The main method

By default Quarkus will automatically generate a main method, that will bootstrap Quarkus and then just wait for shutdown to be initiated. Let’s provide our own main method:

  1. package om.acme;
  2. import io.quarkus.runtime.annotations.QuarkusMain;
  3. import io.quarkus.runtime.Quarkus;
  4. @QuarkusMain (1)
  5. public class Main {
  6. public static void main(String ... args) {
  7. System.out.println("Running main method");
  8. Quarkus.run(args); (2)
  9. }
  10. }
1This annotation tells Quarkus to use this as the main method, unless it is overridden in the config
2This launches Quarkus

This main class will bootstrap Quarkus and run it until it stops. This is no different to the automatically generated main class, but has the advantage that you can just launch it directly from the IDE without needing to run a Maven or Gradle command.

It is not recommenced to do any business logic in this main method, as Quarkus has not been set up yet, and Quarkus may run in a different ClassLoader. If you want to perform logic on startup use an io.quarkus.runtime.QuarkusApplication as described below.

If we want to actually perform business logic on startup (or write applications that complete a task and then exit) we need to supply a io.quarkus.runtime.QuarkusApplication class to the run method. After Quarkus has been started the run method of the application will be invoked. When this method returns the Quarkus application will exit.

If you want to perform logic on startup you should call Quarkus.waitForExit(), this method will wait until a shutdown is requested (either from an external signal like when you press Ctrl+C or because a thread has called Quarkus.asyncExit()).

An example of what this looks like is below:

  1. package com.acme;
  2. import io.quarkus.runtime.Quarkus;
  3. import io.quarkus.runtime.QuarkusApplication;
  4. import io.quarkus.runtime.annotations.QuarkusMain;
  5. @QuarkusMain
  6. public class Main {
  7. public static void main(String... args) {
  8. Quarkus.run(MyApp.class, args);
  9. }
  10. public static class MyApp implements QuarkusApplication {
  11. @Override
  12. public int run(String... args) throws Exception {
  13. System.out.println("Do startup logic here");
  14. Quarkus.waitForExit();
  15. return 0;
  16. }
  17. }
  18. }

Injecting the command line arguments

It is possible to inject the arguments that were passed in on the command line:

  1. @Inject
  2. @CommandLineArguments
  3. String[] args;

Listening for startup and shutdown events

Create a new class named AppLifecycleBean (or pick another name) in the org.acme.lifecycle package, and copy the following content:

  1. package org.acme.lifecycle;
  2. import javax.enterprise.context.ApplicationScoped;
  3. import javax.enterprise.event.Observes;
  4. import io.quarkus.runtime.ShutdownEvent;
  5. import io.quarkus.runtime.StartupEvent;
  6. import org.jboss.logging.Logger;
  7. @ApplicationScoped
  8. public class AppLifecycleBean {
  9. private static final Logger LOGGER = Logger.getLogger("ListenerBean");
  10. void onStart(@Observes StartupEvent ev) { (1)
  11. LOGGER.info("The application is starting...");
  12. }
  13. void onStop(@Observes ShutdownEvent ev) { (2)
  14. LOGGER.info("The application is stopping...");
  15. }
  16. }
  1. Method called when the application is starting

  2. Method called when the application is terminating

The events are also called in dev mode between each redeployment.
The methods can access injected beans. Check the AppLifecycleBean.java class for details.

What is the difference from @Initialized(ApplicationScoped.class) and @Destroyed(ApplicationScoped.class)

In the JVM mode, there is no real difference, except that StartupEvent is always fired after @Initialized(ApplicationScoped.class) and ShutdownEvent is fired before @Destroyed(ApplicationScoped.class). For a native executable build, however, @Initialized(ApplicationScoped.class) is fired as part of the native build process, whereas StartupEvent is fired when the native image is executed. See Three Phases of Bootstrap and Quarkus Philosophy for more details.

In CDI applications, an event with qualifier @Initialized(ApplicationScoped.class) is fired when the application context is initialized. See the spec for more info.

Using @Startup to initialize a CDI bean at application startup

A bean represented by a class, producer method or field annotated with @Startup is initialized at application startup:

  1. package org.acme.lifecycle;
  2. import javax.enterprise.context.ApplicationScoped;
  3. @Startup (1)
  4. @ApplicationScoped
  5. public class EagerAppBean {
  6. private final String name;
  7. EagerAppBean(NameGenerator generator) { (2)
  8. this.name = generator.createName();
  9. }
  10. }
  1. For each bean annotated with @Startup a synthetic observer of StartupEvent is generated. The default priority is used.

  2. The bean constructor is called when the application starts and the resulting contextual instance is stored in the application context.

@Dependent beans are destroyed immediately afterwards to follow the behavior of observers declared on @Dependent beans.
If a class is annotated with @Startup but with no scope annotation then @ApplicationScoped is added automatically.

Package and run the application

Run the application with: ./mvnw compile quarkus:dev, the logged message is printed. When the application is stopped, the second log message is printed.

As usual, the application can be packaged using ./mvnw clean package and executed using the -runner.jar file. You can also generate the native executable using ./mvnw clean package -Pnative.

Launch Modes

Quarkus has 3 different launch modes, NORMAL (i.e. production), DEVELOPMENT and TEST. If you are running quarkus:dev then the mode will be DEVELOPMENT, if you are running a JUnit test it will be TEST, otherwise it will be NORMAL.

Your application can get the launch mode by injecting the io.quarkus.runtime.LaunchMode enum into a CDI bean, or by invoking the static method io.quarkus.runtime.LaunchMode.current().

Graceful Shutdown

Quarkus includes support for graceful shutdown, this allows Quarkus to wait for running requests to finish, up till a set timeout. By default this is disabled, however you can configure this by setting the quarkus.shutdown.timeout config property. When this is set shutdown will not happen until all running requests have completed, or until this timeout has elapsed. This config property is a duration, and can be set using the standard java.time.Duration format, if only a number is specified it is interpreted as seconds.

Extensions that accept requests need to add support for this on an individual basis. At the moment only the HTTP extension supports this, so shutdown may still happen when messaging requests are active.