You must never throw an OOM error, let the application throw it. Also, you must not handle errors, they're meant to terminate the application.
–
Luiggi MendozaJul 11 '13 at 17:41

Thanks for your response! Could you please clarify (a) why OOM should not be thrown from my JNI code? e.g. here they even provided a handy method to throw specifically OOM: stackoverflow.com/questions/230689/… (b) what specifically do you mean with letting application throw it?
–
user2573701Jul 11 '13 at 17:56

From what you seem to say, such an error is not recoverable; you should probably go with a RuntimeException, then. An allocation failure from native code does not prevent the JVM to work, but prevents your application from operating normally. If the JVM itself fails to allocate, you'll see an Error soon enough anyway.
–
fgeJul 11 '13 at 17:59

It should extend Error and not RuntimeException. Otherwise it would be caught by catch handlers for Exception which is usually not what you want when you're out of memory. (OutOfMemoryError is also an Error and not a RuntimeException)
–
main--Jul 11 '13 at 19:01

Thanks! "...Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector..." <= it looks like the key is what is meant by JVM from Java code perspective here: for me it could be (a) JVM, (b) JVM + all loaded native libraries (including mine).
–
user2573701Jul 11 '13 at 21:23

1

Here is more info on OOM: docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-VM/html/… It says that OOM can have several reasons. It has this bit: "3.1 ...A java.lang.OutOfMemoryError can also be thrown by native library code when a native allocation cannot be satisfied, for example, if swap space is low..." Is it about native libs written by application developers? Is 3.1.5 specifically for my case? Or is it about native libs that are part of JVM only?
–
user2573701Jul 11 '13 at 21:27

Also, yes, failure to allocate memory is non-recoverable. The best option a Java application using the lib has is to shutdown gracefully (to be restarted properly).
–
user2573701Jul 11 '13 at 21:32