Out of memory means the java heap is full and garbage collecting it doesn't release a significant amount of that.
The java heap is its own, more or less constant sized batch of memory. It's, at its largest, equal to whatever you passed with the -Xmx
option (e.g. if you run java -Xmx1g
it's 1 gigabyte worth of memory). If you don't use the -Xmx
option it depends on your platform and the mode the JVM is in, but, oversimplifying quite a bit, it's still not quite 'as much as your machine can handle'.
More generally most OS platforms (notably, not iOS) use swap: You have huge swaths of apparent memory because the system will shift pages to disk and back as needed. A JVM doesn't take that much memory (JVMs would perform very very badly) - instead of getting stuck swapping memory pages between disk and main memory, it just aborts with an OutOfMemory.
The point is: The system is just peachy fine and can run whatever you want.
The -XX:OnOutOfMemoryError
runs a system command. Not java code. Even if you use it to run e.g. java -jar myjar.jar OutOfMemoryTrigger
, that starts an entirely new JVM completely separate from the OOMing JVM. Your host system might not be able to do that (for example, if you have no swap and you gave every inch of RAM to the OOMing JVM). In that case, on some OSes your OOMing JVM gets hardkilled by the OS first which is a bit awkward - it's also possible the JVM will wipe out its heap (it's dying/dead - there is no point to it now) and then run the OnOOM command.
OnOutOfMemoryError's purpose is to trigger e.g. a watchdog - something that logs a problem or sends a notification to sysadmins that the system has gone down and needs urgent attention.
The heap dump thing is easy - the code that does that isn't java code (it's the JVM core code), that code is already (and always) in memory (it's basically java.exe
itself, not any code from jars/jmods/class files), and only uses memory the system always reserves for core ops. Using this option does not mean that your JVM has a few megs less vs. not using this option.