0

I am creating standalone spring boot java app, where scheduler, database driven event are handled. I am using spring boot 2.1.1, where I want my standalone java application to run without exit in my appliction. I do not want to rely on OS specific tools like nohup,javaw etc. I tried using spring-boot-web and embedded containers (tomcat/jetty), just to make application run, when main method is executed. But it adds unwanted dependencies and sticked to console from where java -jar is get executed. What is better way to do this, which spring or java provides?.

Sathish
  • 69
  • 9
AnantN
  • 1
  • 2
  • 1
    Why do you want to keep it running? If it is not a web application it should just be triggered, process and exit. You can call it again when required, like a library. – Ubercool Jan 10 '19 at 06:16
  • The reason for keeping it run: the application executes some scheduled tasks and events read from DB. – AnantN Jan 11 '19 at 06:27
  • 1
    Consider enabling scheduling and use task scheduler which will keep running and prevent your application from shutting down. – Ubercool Jan 11 '19 at 09:57
  • What @Ubercool said - enable task scheduling with a non-daemon thread pool and schedule tasks on it. This will prevent your application from shutting down. – Boris the Spider Jan 12 '19 at 18:34
  • Enabling scheduler is cool option, provided at least one scheduler task be always running – AnantN Jan 17 '19 at 06:52
  • see here: https://stackoverflow.com/questions/28017784/how-to-prevent-spring-boot-daemon-server-application-from-closing-shutting-down/37303427 – Alex Cumarav Apr 12 '20 at 08:35

1 Answers1

2

The application will exit, when the last non-daemon thread exits. This is the time, when the application context will be closed. You can prevent that, if you create a non-daemon thread yourself, which will wait for the context to be closed programatically (e.g. by a signal ctrl+c).

@Bean
public DisposableBean contextShutdownGate(ApplicationContext context) {
    CountDownLatch latch = new CountDownLatch(1);
    Thread await = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                LOGGER.error("contextAwait interrupted", e);
            }
        }
    }, "contextAwait-" + context.getId() + "-" + context.getStartupDate());
    await.setDaemon(false);
    await.start();
    return () -> {
        latch.countDown();
    };
}
Martin Theiss
  • 775
  • 4
  • 5