'Best practice for @SpringBoot application to run indefinitely

I have a legacy app I am migrating to SpringBoot. It spins up a number Kafka consumers, each on a separate thread, and processes the events consumed. It does not run on a web-server.

In order to prevent the application from immediately exiting when launched, a call is made to Thread.currentThhread().join().

This works as desired, but isn't playing nicely with my @SpringBootTest which runs on the same thread, and so is also suspended.

I've never had to address this issue working with webapps, and have solved it before, but just can't recall how. Only answers I find online say to include the spring-boot-starter-web dependency, but I don't want to hoof in a web-server to fix this issue when I'm certain there is an elegant solution. Can anyone lend me a hand?

@SpringBootApplication
public class Applicaton {

  public static void main(String[] args) {
    new SpringApplicationBuilder(Application.class)
        .web(WebApplicationType.NONE)
        .run(args);
  }

  @Bean
  public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

      try (ConsumerCoordinator coordinator =
          new ConsumerCoordinator(...) {

          coordinator.startup();  //launches consumer threads
          Thread.currentThread().join();

      } catch (Exception e) {
        logger.error("Event kafka importer failed", e);
      }
    };
  }

}


Solution 1:[1]

Damn, I'm stupid sometimes. The ConsumerCoordinator is obviously a closeable resource. If I take the Thread.currentThhread().join() out, execution runs to the end of the try clause and the ConsumerCoordinator is closed, effectively shutting down all threads.

Rewriting the try clause fixes the issue.

try {
   new ConsumerCoordinator(...).startup();  //launches consumer threads
 } catch (Exception e) {
   logger.error("Event kafka importer failed", e);
 }

So the legacy approach only worked because there weren't any component tests that exercised it! Any that shows exactly why I'm going through this refactoring exercise.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 elgaz