Home > Software engineering >  Stop Java service gracefully, executed using nohoup command
Stop Java service gracefully, executed using nohoup command

Time:05-05

I am a beginner in java spring-boot

when I start the java server through

nohup java -jar demo-0.0.1-SNAPSHOT.jar

command my threads start their operations

After sometimes when I stop my server using

kill -9 processid

So my running thread data are lost.

I want to maintain a thread flag in the database whenever server stops.

I have tried to achieve the above scenario in following this tutorial Spring Boot Shutdown. It works properly but it breaks my security as anyone can use this API to stop my server.

I need a way to terminate my server gracefully and call ContextClosedEvent class.

CodePudding user response:

No graceful shutdown support provided by Spring Boot is going to work if you use kill -9. That is SIGKILL, which can't be caught, blocked, or ignored, so of course your application can't do anything in response to it.

Use kill -SIGTERM to allow shutdown hooks to execute in your Java runtime.

Avoid magic numbers like 15 and 9; use meaningful symbols like SIGTERM instead.

CodePudding user response:

If you are using Spring Boot version from 2.3 and later, special configuration for graceful shutdown should be added to application.yml:

server:
  shutdown: graceful

From java doc:

The WebServer should support graceful shutdown, allowing active requests time to complete

Another option is immediate:

The WebServer should shut down immediately

Additional resource Shutdown Spring Boot Applications Gracefully

  • Related