This is a theoretical question. I am just curios that if Java has a mechanism for garbage collection to free the memory, then why does still OutOfMemoryError
occur?
I searched SO for this but could get these links
Is the garbage collector guaranteed to run before Out of Memory Error?
Garbage collection before OutOfMemoryError
These do not answer my question specifically. If Java allows memory so well by using garbage collection, then why does OutOfMemoryError
occur?
Drawbacks of garbage collection in Java Garbage collectors bring some runtime overhead that is out of the programmer's control. This could lead to performance problems for large applications that scale large numbers of threads or processors, or sockets that consume a large amount of memory.
Garbage collection makes Java memory efficient because it removes the unreferenced objects from heap memory and makes free space for new objects. The Java Virtual Machine has eight types of garbage collectors.
The most common performance problem associated with Java™ relates to the garbage collection mechanism. If the size of the Java heap is too large, the heap must reside outside main memory. This causes increased paging activity, which affects Java performance.
7. What happens to the thread when garbage collection kicks off? Explanation: The thread is paused when garbage collection runs which slows the application performance.
An OutOfMemoryError can occur if none of the objects in memory is eligible for garbage collection. For example:
List<MyClass> hellos = new ArrayList<>();
for (;;) {
hellos.add(new MyClass());
}
This creates a list and keeps adding MyClass
objects to it until memory runs out. None of the objects is eligible for garbage collection because there are references to all of them.
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