title: Reliably restarting a java process after a crash in a shell script
body: <p>I have a jar that when run, goes through the files in a directory and processes 10 of them before exiting.</p>
  
  <p>I have a shell script that looks something like this:</p>
  
  <pre><code>while true;
  do java -jar myjar.jar
  sleep2;
  done
  </code></pre>
  
  <p>I have another shell script that runs the previous one on startup like so:</p>
  
  <pre><code>nohup loopscript.sh &gt; /var/log/error.log
  </code></pre>
  
  <p>The problem is that sometimes the jar crashes when it needs more memory than the system has, and the entire loop seems to stop running. My log file ends with a stack trace when the memory cap is hit.</p>
  
  <p>How can I reliably restart the loop after a crash? I read <a href="https://stackoverflow.com/questions/696839/how-do-i-write-a-bash-script-to-restart-a-process-if-it-dies">elsewhere on SO</a> to do something like</p>
  
  <pre><code>until myserver; do
      echo "Server 'myserver' crashed with exit code $?.  Respawning.." &gt;&amp;2
      sleep 1
  done
  </code></pre>
  
  <p>But this only works if myserver is itself in a loop, and I'm intentionally halting the jar after 10 runs to force garbage collection and reduce the chance of a crash midway. Is my logic flawed? Should I just put the jar into a loop and use the above method of restarting it when it crashes?</p>