How to restart java app managed by systemd on OutOfMemory errors

6,651

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
Share:
6,651

Related videos on Youtube

qwazer
Author by

qwazer

Updated on September 18, 2022

Comments

  • qwazer
    qwazer over 1 year

    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
      qwazer over 7 years
      @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.
  • Bill
    Bill about 6 years
    -XX:+CrashOnOutOfMemoryError is the correct version of the first option.
  • Federico Sierra
    Federico Sierra about 6 years
    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.