5

I have the java app (on top of Spring Boot framework) installed as systemd service.

[Unit]
Description=${module_name}-service
Requires=network.target
After=syslog.target

[Service]
User=${user_name}
ExecStart=/opt/${module_name}/${module_name}-${version}.jar
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

How to manage service restarts of some conditions, for example auto-restart after OutOfMemory errors

qwazer
  • 207
  • 1
  • 3
  • 7
  • 1
    " auto-restart after OutOfMemory errors" May I suggest you better fix the memory problems? Swallowing aspirin against the pain won't fix the broken leg. –  Jan 17 '17 at 10:09
  • 1
    Fair enough. My experience with these "we'll do this for now and fix it later" - patches is that they **will** be permanent because you'll always have something with higher prio as long as it "works". But if it eventually will blow up in your face it could be hard to explain why this has not been fixed properly. Don't get me wrong - I am not trying to be rude here. Just telling you my experience with such workarounds. So if you do that, I suggest you really **also** push for solving the actual problem. –  Jan 17 '17 at 10:18
  • 1
    @Fildor, Yes, but sometime developers are busy or unavailable, so It can be desirable to swallow aspirin to make life more painless on the way to a doctor. – qwazer Jan 17 '17 at 10:14

1 Answers1

8

Like Fildor say I suggest you fix the memory problems.

After that a possible solution is:

If you are using Java prior 8u92 you can add to the JVM the following argument:

java -jar <jar-name> -XX:OnOutOfMemoryError="kill -9 %p"

in Java version 8u92 or higher you can use -XX:+CrashOnOutOfMemory or -XX:+ExitOnOutOfMemoryError

Then configure your service to restart on crash:

Restart=on-failure

or

Restart=always
Federico Sierra
  • 3,589
  • 1
  • 20
  • 26
  • `-XX:+CrashOnOutOfMemoryError` is the correct version of the first option. – BillRobertson42 Mar 19 '18 at 07:03
  • Since JDK 8u92 `CrashOnOutOfMemoryError` - If this option is enabled, when an out-of-memory error occurs, the JVM crashes and produces text and binary crash files (if core files are enabled). With `ExitOnOutOfMemoryError` JVM exits on the first occurrence of an out-of-memory error. It can be used if you prefer restarting an instance of the JVM rather than handling out of memory errors. – Federico Sierra Mar 19 '18 at 12:51