In case the heap is full, the JVM throws an
OutOfMemoryError
. But is it assured that a (full) garbage collection always takes place before such an exception is thrown?
This would mean that the memory is full only with strong referenced objects (or reachable by GC Roots) when the exception is thrown.
Edit: Assume the Sun JVM - HotSpot is in discussion.
No, garbage collection cannot guarantee that your application will not run out of memory. It will not even guarantee that your application will not run out of memory when memory is available.
The garbage collector runs immediately the system is out of memory before an OutOfMemoryException is thrown by the JVM. Option D is wrong. If this were the case then the garbage collector would actively hang onto objects until a program finishes - this goes against the purpose of the garbage collector.
Garbage Collection makes memory management in Java efficient as it removes unreferenced objects from the heap memory without the interference of the programmer. As Garbage collection is automatic and is a part of JVM, no extra efforts are needed from the programmer to reclaim memory or destruct objects.
The garbage collector will usually be run before an OutOfMemoryError is thrown. However you might get an OOME without a GC if you
The Java Machine Specification states in section 6.3 (emphasis mine):
OutOfMemoryError
: The Java virtual machine implementation has run out of either virtual or physical memory, and the automatic storage manager was unable to reclaim enough memory to satisfy an object creation request.
So the JVM does give a guarantee that it will try what it can to free up memory through garbage collection before it throws an OOME.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With