corda/sgx-jvm/avian/test/OutOfMemory.java

63 lines
1.2 KiB
Java
Raw Normal View History

rework VM exception handling; throw OOMEs when appropriate This rather large commit modifies the VM to use non-local returns to throw exceptions instead of simply setting Thread::exception and returning frame-by-frame as it used to. This has several benefits: * Functions no longer need to check Thread::exception after each call which might throw an exception (which would be especially tedious and error-prone now that any function which allocates objects directly or indirectly might throw an OutOfMemoryError) * There's no need to audit the code for calls to functions which previously did not throw exceptions but later do * Performance should be improved slightly due to both the reduced need for conditionals and because undwinding now occurs in a single jump instead of a series of returns The main disadvantages are: * Slightly higher overhead for entering and leaving the VM via the JNI and JDK methods * Non-local returns can make the code harder to read * We must be careful to register destructors for stack-allocated resources with the Thread so they can be called prior to a non-local return The non-local return implementation is similar to setjmp/longjmp, except it uses continuation-passing style to avoid the need for cooperation from the C/C++ compiler. Native C++ exceptions would have also been an option, but that would introduce a dependence on libstdc++, which we're trying to avoid for portability reasons. Finally, this commit ensures that the VM throws an OutOfMemoryError instead of aborting when it reaches its memory ceiling. Currently, we treat the ceiling as a soft limit and temporarily exceed it as necessary to allow garbage collection and certain internal allocations to succeed, but refuse to allocate any Java objects until the heap size drops back below the ceiling.
2010-12-27 22:55:23 +00:00
public class OutOfMemory {
// assume a 128MB heap size:
private static final int Padding = 120 * 1024 * 1024;
private static class Node {
Object value;
Node next;
}
private static void bigObjects() {
Object[] root = null;
while (true) {
Object[] x = new Object[1024 * 1024];
x[0] = root;
root = x;
}
}
private static void littleObjects() {
byte[] padding = new byte[Padding];
Node root = null;
while (true) {
Node x = new Node();
x.next = root;
root = x;
}
}
private static void bigAndLittleObjects() {
byte[] padding = new byte[Padding];
Node root = null;
while (true) {
Node x = new Node();
x.value = new Object[1024 * 1024];
x.next = root;
root = x;
}
}
public static void main(String[] args) {
try {
bigObjects();
throw new RuntimeException();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
try {
littleObjects();
throw new RuntimeException();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
try {
bigAndLittleObjects();
throw new RuntimeException();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
}