Auto restart jar on OutOfMemoryError Linux

2019-08-13 00:14发布

问题:

How can i auto-restart the runnable jar file in Linux.

I am running jar in linux VPS in a separate screen but it stops after some time due to OUTOFMEMORYERROR Java heap space.

回答1:

Write a simple launcher which will restart the application once it came down. Something like this:

#!/bin/sh

TEMPFILE=`mktemp`
while true ; do
  echo "`date` Starting application" >> $TEMPFILE
  java -XX:OnOutOfMemoryError="kill -9 %p" -jar application.jar
  sleep 5
done

Just to be sure that the VM comes done correcly, you might want to consider the following around your main loop:

try {
    // main loop
    businessLogic();
} catch (OutOfMemoryError E) {
    System.exit(1);
}

Edit: I've personally succesfully used the Java Service Wrapper for restarting a now and then failing apache tomcat which suffered from memory leaks after applications have been redeployed too much. You might want to take a look at it, it's pretty straight forward.



回答2:

Have you tried to by allocating more memory to jvm ? If still problem persist then You can aasociate shutdown hook but there is no gaurantee it will execute always. You can invoke other process from it which will star your program again after some delay



回答3:

try this: -XX:OnOutOfMemoryError="<cmd args>; <cmd args>" Write a shell script to "kill -TERM pid" and then start it again and put the script into cmd part of the command line option. More or less that's it but you will need to know the pid of the processes (or rely on killall or ps, etc)

Also you can use monit to periodically check if the application is running. More or less those are standard solutions. I, myself, use monitoring daemon to notify via email/sms when memory is low so a proper examination can be taken and if there is a leak to be fixed. Bluntly dumping the heap sucks when you have dozens of GB of it.