Last active
August 21, 2018 09:50
-
-
Save thhart/65efc4b6a113995a0bf3f9571ed905d8 to your computer and use it in GitHub Desktop.
How to catch an OutOfMemoryError in Java, an approach. This code is based on Log4J but should work with any other logger as well. Every try/catch should contain a logger handler.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.log4j.*; | |
import org.apache.log4j.spi.LoggingEvent; | |
private static String MEMORY_STRING = "OUT OF MEMORY ERROR MONITORED, EXITING"; | |
static { | |
Logger.getRootLogger().addAppender(new AsyncAppender() { | |
public void append(LoggingEvent event) { | |
if(event.getThrowableInformation() != null) { | |
if(event.getThrowableInformation().getThrowable() instanceof OutOfMemoryError) { | |
exitingDueMemory(); | |
} | |
} | |
} | |
}); | |
Thread.setDefaultUncaughtExceptionHandler((t, e) -> { | |
if (e instanceof OutOfMemoryError) { | |
exitingDueMemory(); | |
} else { | |
final RuntimeException exception = new RuntimeException("warning, uncaught exception occurred", e); | |
logger.error(exception, exception); | |
} | |
}); | |
} | |
private static void exitingDueMemory() { | |
System.err.println(MEMORY_STRING); | |
logger.fatal(MEMORY_STRING); | |
System.exit(42); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment