I came up with the following method. I am getting a stackoverflow error. Is there a faster way?
static void looper(){
long a = 0;
a++;
System.out.println(a);
looper();
}
I came up with the following method. I am getting a stackoverflow error. Is there a faster way?
static void looper(){
long a = 0;
a++;
System.out.println(a);
looper();
}
A fast way to get an OutOfMemoryError
is:
final int[] memoryGrave = new int[Integer.MAX_VALUE];
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
(You can find more about max array sizes in this question: Do Java arrays have a maximum size?)
But this might not be what you're looking for, since it is possible that the JVM checks the requested array size and throws that error before actually running out of memory.
But you can alter that code a bit, to do that "correctly":
final List<int[]> memoryGrave = new ArrayList<>();
while(true) {
memoryGrave.add(new int[Integer.MAX_VALUE - 5]);
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
But if this is "fastest way" to get that error (and really run out of memory) can still be discussed.
When you wrap the above code into a try/finally
, then you can measure the time it needs to throw that error:
long start = System.currentTimeMillis();
try {
final List<int[]> memoryGrave = new ArrayList<>();
while (true) {
memoryGrave.add(new int[Integer.MAX_VALUE - 5]);
}
} finally {
System.out.println(System.currentTimeMillis() - start);
}
On my machine it needs round about 30 ms.