5

I've encountered OutOfMemoryError in my JAVA program. It is OK that OutOfMemoryError happened, but I'd like to log it when it happens. I have used -XX:OnOutOfMemoryError options to detect that it happened, but it doesn't log stacktrace information which is printed to console. I tried to use redirection to log this console output, but 2>&1, 2>, and all other options failed log this output and it just printed to console. Is there any way to log this stacktrace information? I've been googling and searching in stackoverflow.com but couldn't find answer. Please advice.

  • Heap Dump is not my option, either. I don't have so much space so can't risk such huge file :'( I just need to log stacktrace information.

Thank you!

Daniel Kim
  • 51
  • 3

1 Answers1

6
  • Option 1: You could use OnOutOfMemoryError hook combined with jstack to get stacktrace of your process:

    "-XX:OnOutOfMemoryError=jstack -l %p"

    note: on production you most likely will have separate shell script for that to avoid problem with jstack coming from different java versions.

  • Option 2: You could use setUncaughtExceptionHandler to catch all exception and check for OutOfMemoryError specifically:

    Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
    
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
    ...
    
Petro Semeniuk
  • 6,970
  • 10
  • 42
  • 65