Skip to content

Instantly share code, notes, and snippets.

@thhart
Last active August 21, 2018 09:50
Show Gist options
  • Save thhart/65efc4b6a113995a0bf3f9571ed905d8 to your computer and use it in GitHub Desktop.
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.
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