Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of JVM during out of memory error? List s = new ArrayList<String>();

Tags:

java

try {
    for(;;) {
        s.add("Pradeep");
    }
} finally {
    System.out.println("In Finally");
}

In the try block the jvm runs out of memory,then how is jvm excuting finally block when it has no memory?

Output:

In Finally
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
like image 223
Rekha Avatar asked Oct 13 '11 11:10

Rekha


People also ask

What happens when JVM runs out of memory?

In a very extreme condition, you can run out of free memory while the JVM is running, and at the same time the JVM requires more memory for its internal operation (not the heap space) - then the JVM tells you it needed more memory, but could not get any, and terminates, or it will crash outright.

Which error is thrown when Java is out of memory?

One common indication of a memory leak is the java. lang. OutOfMemoryError exception. Usually, this error is thrown when there is insufficient space to allocate an object in the Java heap.

In which memory is ArrayList stored?

ArrayLists use contiguous memory. All elements in the ArrayList are located next to each other in the same memory space.


1 Answers

Presumably the System.out.println call requires less memory than the s.add("Pradeep") call.

If s is an ArrayList for instance, the s.add call may cause the list to attempt to double up it's capacity. This is possibly a quite memory demanding operation, thus it is not very surprising that the JVM can continue executing even if it can't perform such relatively expensive task.

like image 93
aioobe Avatar answered Nov 12 '22 06:11

aioobe